﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using MS_Enitity;
using HalconDotNet;
using System.IO;
using MvCamCtrl.NET;
using System.Runtime.InteropServices;
using System.IO.Ports;
using xktNodeSettings.Node.Variable;
using xktNodeSettings.Node.Device;
using xktNodeSettings;
using xktComm.Common;
using xktComm.DataConvert;
using xktComm.PLC.Melsec;
using TextFile;
using System.Net.Sockets;
using System.Net;
using System.Text.RegularExpressions;
using System.Globalization;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Web;
using Newtonsoft.Json;
using SokectHelper;
using System.Collections.Concurrent;
using MS_Enitity.EAP;
using rest;

namespace MS_UI
{



    public enum Operation_mode
    {

        Manual = 1,
        Auto = 2
    }


    public struct SYSTEMTIME
    {
        public ushort wYear;
        public ushort wMonth;
        public ushort wDayOfWeek;
        public ushort wDay;
        public ushort wHour;
        public ushort wMinute;
        public ushort wSecond;
        public ushort wMilliseconds;

        /// <summary>
        /// 从System.DateTime转换。
        /// </summary>
        /// <param name="time">System.DateTime类型的时间。</param>
        public void FromDateTime(DateTime time)
        {
            wYear = (ushort)time.Year;
            wMonth = (ushort)time.Month;
            wDayOfWeek = (ushort)time.DayOfWeek;
            wDay = (ushort)time.Day;
            wHour = (ushort)time.Hour;
            wMinute = (ushort)time.Minute;
            wSecond = (ushort)time.Second;
            wMilliseconds = (ushort)time.Millisecond;
        }
        /// <summary>
        /// 转换为System.DateTime类型。
        /// </summary>
        /// <returns></returns>
        public DateTime ToDateTime()
        {
            return new DateTime(wYear, wMonth, wDay, wHour, wMinute, wSecond, wMilliseconds);
        }
        /// <summary>
        /// 静态方法。转换为System.DateTime类型。
        /// </summary>
        /// <param name="time">SYSTEMTIME类型的时间.</param>
        /// <returns></returns>
        public static DateTime ToDateTime(SYSTEMTIME time)
        {
            return time.ToDateTime();
        }
    }




    public partial class FrmMain : Form
    {

        [DllImport("Kernel32.dll")]
        public static extern bool SetLocalTime(ref SYSTEMTIME Time);
        [DllImport("Kernel32.dll")]
        public static extern void GetLocalTime(ref SYSTEMTIME Time);





        #region  定义变量

        private bool firstTime =true;
        private short Port1_Loader_Rack_oldIndex;
        private short Port1_Task_Download_oldIndex;
        private short Port1_LoadPCB_oldIndex;
        private short Port1_PanelIDReport_oldIndex;
        private short Port1_LotFinishReport_oldIndex;
        private short Port1_Unloder_Rack_oldIndex;
        private short Port1_Allow_Into_oldIndex;

        private short Port2_Loader_Rack_oldIndex;
        private short Port2_Task_Download_oldIndex;
        private short Port2_LoadPCB_oldIndex;
        private short Port2_PanelIDReport_oldIndex;
        private short Port2_LotFinishReport_oldIndex;
        private short Port2_Unloder_Rack_oldIndex;
        private short Port2_Allow_Into_oldIndex;



        private short Port3_Loader_Rack_oldIndex;
        private short Port3_Task_Download_oldIndex;
        private short Port3_LoadPCB_oldIndex;
        private short Port3_PanelIDReport_oldIndex;
        private short Port3_LotFinishReport_oldIndex;
        private short Port3_Unloder_Rack_oldIndex;
        private short Port3_Allow_Into_oldIndex;


        private short DeviceStatusReport_oldIndex;

        private bool Port1_Loader_Rack_Trigger;
        private bool Port1_Task_Download_Trigger;
        private bool Port1_LoadPCB_Trigger;
        private bool Port1_PanelIDReport_Trigger;
        private bool Port1_LotFinishReport_Trigger;
        private bool Port1_Unloder_Rack_Trigger;
        private bool Port1_Allow_Into_Trigger;


        private bool Port2_Loader_Rack_Trigger;
        private bool Port2_Task_Download_Trigger;
        private bool Port2_LoadPCB_Trigger;
        private bool Port2_PanelIDReport_Trigger;
        private bool Port2_LotFinishReport_Trigger;
        private bool Port2_Unloder_Rack_Trigger;

        private bool Port3_Loader_Rack_Trigger;
        private bool Port3_Task_Download_Trigger;
        private bool Port3_LoadPCB_Trigger;
        private bool Port3_PanelIDReport_Trigger;
        private bool Port3_LotFinishReport_Trigger;
        private bool Port3_Unloder_Rack_Trigger;

        private bool DeviceStatusReport_Trigger;








        private int EquipmentAlarm1_old;
        private int EquipmentAlarm2_old;






        private string EQPType = "收板机";

        private string SimulationTest = "启用";

        public string up_sys_name = "收放板机上位机系统";
        public string line_code = "ABC";
        public string station_code = "20240829";
        public string station_type = "SB";

        public string HAlarm_Msg0 = "急停报警";
        public string HAlarm_Msg1 = "严重报警2";
        public string HAlarm_Msg2 = "严重报警3";
        public string HAlarm_Msg3 = "严重报警4";
        public string HAlarm_Msg4 = "严重报警5";
        public string HAlarm_Msg5 = "严重报警6";
        public string HAlarm_Msg6 = "严重报警7";
        public string HAlarm_Msg7 = "严重报警8";
        public string HAlarm_Msg8 = "严重报警9";
        public string HAlarm_Msg9 = "严重报警10";
        public string HAlarm_Msg10 = "严重报警11";
        public string HAlarm_Msg11 = "严重报警12";
        public string HAlarm_Msg12 = "严重报警13";
        public string HAlarm_Msg13 = "严重报警14";

        public string LAlarm_Msg0 = "安全门打开";
        public string LAlarm_Msg1 = "进入危险区域";
        public string LAlarm_Msg2 = "一般报警3";
        public string LAlarm_Msg3 = "一般报警4";
        public string LAlarm_Msg4 = "一般报警5";
        public string LAlarm_Msg5 = "一般报警6";
        public string LAlarm_Msg6 = "一般报警7";
        public string LAlarm_Msg7 = "一般报警8";


        public HikRestInterface client;
        private string EAPserverIP;
        private string EAPserverPort;
        private string EAPBaseURL;
        private string ServerURL;





        //定义BackgroundWorker实例
        BackgroundWorker bw = new BackgroundWorker();

        private bool oldindexInitial;

        //定义文件路径
        private string FilePath = System.Windows.Forms.Application.StartupPath + "\\ConfigFile\\";

        //定义文件路径
        private string SysparamPath = System.Windows.Forms.Application.StartupPath + "\\param.ini";


        //定义配置文件的路径
        private string SettingsPath = Application.StartupPath + "\\Settings\\melsec.xml";

        //上次报警值
        public Dictionary<string, int> LastValue = new Dictionary<string, int>();

        // 报警内容集合
        List<string> AlarmList = new List<string>();

        //报警字符串
        string Alarmstrs;

        public static bool PassWorddisable;                //密码暂时屏蔽标志

        public static System.Timers.Timer t = new System.Timers.Timer(600000);

        public void theout(object source, System.Timers.ElapsedEventArgs e)

        {
            PassWorddisable = false;
        }

        #endregion

        #region 创建主画面
        public FrmMain()
        {

            InitializeComponent();

            client = HikRestInterface.getInstance(this);
            client.LogEvent += AddLog;


            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    try
                    {

                        Task.Delay(60 * 1000).Wait();
                        Save();
                    }
                    catch (Exception ex)
                    {
                        AddLog(1, ex.Message);
                    }
                }
            }, TaskCreationOptions.LongRunning);






            //第一步：文件变对象
            try
            {
                CommMethods.MelsecList = MelsecCFG.LoadXmlFile(SettingsPath);
            }

            catch (Exception ex)
            {
                MessageBox.Show("加载配置文件失败:" + ex.Message);
                return;
            }


            ////第二步：初始化工作

            InitialParam();

            ////第三步：通用数据解析及连接
            ConnectAndComm();

            this.Load += FrmMain_Load;

            t.Elapsed += new System.Timers.ElapsedEventHandler(theout);
            t.AutoReset = false;
            //t.Enabled = true;
            t.Start();


            PassWorddisable = false;


        }
        #endregion



        #region 加载窗体 
        void FrmMain_Load(object sender, EventArgs e)
        {
            //DateTime t= DateTime.ParseExact("20221223003912", "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);


            SYSTEMTIME st = new SYSTEMTIME();
            //st.FromDateTime(t);
            ////调用Win32 API设置系统时间
            //SetLocalTime(ref st);

            //  lst_Rcv.OwnerDraw = true;




            this.lbl_date.Text = DateTime.Now.ToShortDateString();
            CommMethods.objFrmMain = this;
            InitialTxt();
            this.timer1.Enabled = true;
            this.timer2.Enabled = true;
            this.timer3.Enabled = true;
            this.timer1.Interval = 500;
            this.timer2.Interval = 500;
            this.timer3.Interval = 1500;




            foreach (Control item in groupBox1.Controls)
            {

                item.Enabled = SimulationTest == "启用" ? true : false;

            }


            lotDatagridviewUpdate();

            InitialAlarm();
            SQLiteHelper.ConStr = "Data Source=" + Application.StartupPath + "\\DataBase\\databaseld;Pooling=true;FailIfMissing=false";

            Task.Run(() => EAPprocess());

            //       Task.Run(() => ConnectEAP());

            client.setServer(EAPserverIP, EAPserverPort, EAPBaseURL);


            this.Restfful();


            //     btn_Connect_Click(null, null);
            //  UpdateCommon(this);   
        }


        #endregion


















        #region 初始化文件信息
        /// <summary>
        /// 初始化文件信息
        /// </summary>
        private void InitialTxt()
        {
            string Path = FilePath + "COM.ini";
            CommMethods.CommInfo = CommMethods.GetFactor(Path);

            IniConfigHelper.filePath = SysparamPath;


            EAPserverIP = IniConfigHelper.ReadIniData("EAP参数", "服务器IP", "");
            EAPserverPort = IniConfigHelper.ReadIniData("EAP参数", "端口号", "");
            EAPBaseURL = IniConfigHelper.ReadIniData("EAP参数", "基地址", "");

            ServerURL = IniConfigHelper.ReadIniData("Web服务端", "服务端URL", "");


            up_sys_name = IniConfigHelper.ReadIniData("设备配置", "系统名称", "");
            line_code = IniConfigHelper.ReadIniData("设备配置", "生产线编号", "");
            station_code = IniConfigHelper.ReadIniData("设备配置", "设备编号", "");
            station_type = IniConfigHelper.ReadIniData("设备配置", "设备类型", "");
            SimulationTest = IniConfigHelper.ReadIniData("设备配置", "模拟测试", "");
            CommMethods.port1Position = IniConfigHelper.ReadIniData("工位信息", "工位1", "");
            CommMethods.port2Position = IniConfigHelper.ReadIniData("工位信息", "工位2", "");
            CommMethods.port3Position = IniConfigHelper.ReadIniData("工位信息", "工位3", "");


            HAlarm_Msg0 = IniConfigHelper.ReadIniData("设备报警信息", "HAlarm_Msg0", "");
            HAlarm_Msg1 = IniConfigHelper.ReadIniData("设备报警信息", "HAlarm_Msg1", "");
            HAlarm_Msg2 = IniConfigHelper.ReadIniData("设备报警信息", "HAlarm_Msg2", "");
            HAlarm_Msg3 = IniConfigHelper.ReadIniData("设备报警信息", "HAlarm_Msg3", "");
            HAlarm_Msg4 = IniConfigHelper.ReadIniData("设备报警信息", "HAlarm_Msg4", "");
            HAlarm_Msg5 = IniConfigHelper.ReadIniData("设备报警信息", "HAlarm_Msg5", "");
            HAlarm_Msg6 = IniConfigHelper.ReadIniData("设备报警信息", "HAlarm_Msg6", "");
            HAlarm_Msg7 = IniConfigHelper.ReadIniData("设备报警信息", "HAlarm_Msg7", "");

            LAlarm_Msg0 = IniConfigHelper.ReadIniData("设备报警信息", "LAlarm_Msg0", "");
            LAlarm_Msg1 = IniConfigHelper.ReadIniData("设备报警信息", "LAlarm_Msg1", "");
            LAlarm_Msg2 = IniConfigHelper.ReadIniData("设备报警信息", "LAlarm_Msg2", "");
            LAlarm_Msg3 = IniConfigHelper.ReadIniData("设备报警信息", "LAlarm_Msg3", "");
            LAlarm_Msg4 = IniConfigHelper.ReadIniData("设备报警信息", "LAlarm_Msg4", "");
            LAlarm_Msg5 = IniConfigHelper.ReadIniData("设备报警信息", "LAlarm_Msg5", "");
            LAlarm_Msg6 = IniConfigHelper.ReadIniData("设备报警信息", "LAlarm_Msg6", "");
            LAlarm_Msg7 = IniConfigHelper.ReadIniData("设备报警信息", "LAlarm_Msg7", "");


            if (File.Exists("concurrentQueue.json"))
            {
                CommMethods.concurrentQueue = JsonConvert.DeserializeObject<ConcurrentQueue<Task_info>>(File.ReadAllText("concurrentQueue.json")) ?? new ConcurrentQueue<Task_info>();
            }

            if (File.Exists("CurrentJobData1.json"))
            {
                CommMethods.Current_task_info1 = JsonConvert.DeserializeObject<Task_info>(File.ReadAllText("CurrentJobData1.json")) ?? new Task_info();
            }
            if (File.Exists("CurrentJobData2.json"))
            {
                CommMethods.Current_task_info2 = JsonConvert.DeserializeObject<Task_info>(File.ReadAllText("CurrentJobData2.json")) ?? new Task_info();
            }

            if (File.Exists("CurrentJobData3.json"))
            {
                CommMethods.Current_task_info3 = JsonConvert.DeserializeObject<Task_info>(File.ReadAllText("CurrentJobData3.json")) ?? new Task_info();
            }


            if (File.Exists("panelList.json"))
            {
                CommMethods.panelList = JsonConvert.DeserializeObject<List<PanelID>>(File.ReadAllText("panelList.json")) ?? new List<PanelID>();
            }


            //       CommMethods.CommonMelsecWrite(CommMethods.CurrentMelsecVarList["队列数量"], (CommMethods.concurrentQueue.Count).ToString());
            //if (EQPType == "投板机")
            //{
            //    while (CommMethods.concurrentQueue.Count > 0)
            //    {
            //        bool result = CommMethods.concurrentQueue.TryDequeue(out var m);
            //    }

            //    Save();
            //    lotDatagridviewUpdate();
            //}

            //Output("加载配置文件完成");
        }
        #endregion

        #region PLC通讯处理
        private void InitialParam()
        {
            if (CommMethods.MelsecList.Count > 0)
            {
                foreach (var dev in CommMethods.MelsecList)
                {
                    foreach (var gp in dev.DeviceGroupList)
                    {
                        foreach (var var in gp.varList)
                        {
                            //报警变量的初始化
                            if (var.Config.AlarmEnable)
                            {
                                if (!CheckVariableMelsecExits(var))
                                {
                                    CommMethods.Alarm_Variable_List.Add(var);
                                }
                            }
                            if (!CommMethods.CurrentMelsecValue.ContainsKey(var.Name))
                            {
                                CommMethods.CurrentMelsecVarList.Add(var.Name, var);
                                CommMethods.CurrentMelsecValue.Add(var.Name, "0");
                            }
                        }
                    }
                }
            }
        }

        private bool CheckVariableMelsecExits(MelsecVariable var)
        {
            for (int i = 0; i < CommMethods.Alarm_Variable_List.Count; i++)
            {
                if (CommMethods.Alarm_Variable_List[i].Name == var.Name)
                {
                    return true;
                }
            }
            return false;
        }

        private void ConnectAndComm()
        {
            if (CommMethods.MelsecList.Count > 0)
            {
                foreach (var item in CommMethods.MelsecList)
                {
                    if (item.IsActive)
                    {
                        //开启多线程
                        item.cts = new System.Threading.CancellationTokenSource();
                        Task.Run(() => GetMelsecValue(item), item.cts.Token);
                    }
                }
            }
        }

        private void GetMelsecValue(NodeMelsec melsec)
        {
            while (!melsec.cts.IsCancellationRequested)
            {
                if (melsec.IsConnected)
                {
                    //读取
                    foreach (var gp in melsec.DeviceGroupList)
                    {
                        if (gp.IsActive)
                        {
                            bool isFX3U = melsec.PlcType == MelsecProtocol.MCA1E;

                            byte[] res;

                            switch (gp.StoreArea)
                            {
                                case MelsecStoreArea.D存储区:
                                case MelsecStoreArea.W存储区:
                                    //数据读取和解析
                                    res = melsec.melsec.ReadBytes(gp.Start, Convert.ToUInt16(gp.Length));
                                    if (res != null)
                                    {
                                        //获取组的开始地址

                                        //D10  10    D15     第几个字节开始解析           D16  12                                    
                                        //D10 D11 D12 D13 D14 D15 D16 D17 D18 D19
                                        //0       2   4        6    8    10

                                        //20个字节   10个 

                                        //D10


                                        int gpstart = GetMelsecStart(isFX3U, gp.Start.Substring(1), gp.StoreArea, melsec.IsFX5UMC);

                                        foreach (var var in gp.varList)
                                        {

                                            if (VerifyMelsecAddress(false, isFX3U, gp.StoreArea, var.Start, melsec.IsFX5UMC, out int start, out int offset))
                                            {
                                                start -= gpstart;
                                                start *= 2;

                                                switch (var.VarType)
                                                {
                                                    case DataType.Bool:
                                                        //先拿到2个字节  根据2个字节中的偏移解析
                                                        var.Value = BitLib.GetBitFrom2ByteArray(res, start, offset, true);
                                                        break;
                                                    case DataType.Byte:
                                                        var.Value = ByteLib.GetByteFromByteArray(res, start);
                                                        break;
                                                    case DataType.Short:
                                                        var.Value = ShortLib.GetShortFromByteArray(res, start, melsec.melsec.DataFormat);
                                                        break;
                                                    case DataType.UShort:
                                                        var.Value = UShortLib.GetUShortFromByteArray(res, start, melsec.melsec.DataFormat);
                                                        break;
                                                    case DataType.Int:
                                                        var.Value = IntLib.GetIntFromByteArray(res, start, melsec.melsec.DataFormat);
                                                        break;
                                                    case DataType.UInt:
                                                        var.Value = UIntLib.GetUIntFromByteArray(res, start, melsec.melsec.DataFormat);
                                                        break;
                                                    case DataType.Float:
                                                        var.Value = FloatLib.GetFloatFromByteArray(res, start, melsec.melsec.DataFormat);
                                                        break;
                                                    case DataType.Double:
                                                        var.Value = DoubleLib.GetDoubleFromByteArray(res, start, melsec.melsec.DataFormat);
                                                        break;
                                                    case DataType.Long:
                                                        var.Value = LongLib.GetLongFromByteArray(res, start, melsec.melsec.DataFormat);
                                                        break;
                                                    case DataType.ULong:
                                                        var.Value = ULongLib.GetULongFromByteArray(res, start, melsec.melsec.DataFormat);
                                                        break;
                                                    case DataType.String:
                                                        var.Value = StringLib.GetStringFromByteArray(res, start, 2 * offset);
                                                        break;
                                                    default:
                                                        break;
                                                }

                                                //数据转换
                                                var.Value = MigrationLib.GetMigrationValue(var.Value, var.Scale, var.Offset);

                                                if (CommMethods.CurrentMelsecValue.ContainsKey(var.Name))
                                                {
                                                    CommMethods.CurrentMelsecValue[var.Name] = var.Value;
                                                }
                                                else
                                                {
                                                    CommMethods.CurrentMelsecValue.Add(var.Name, var.Value);
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        melsec.IsConnected = false;
                                    }
                                    break;
                                case MelsecStoreArea.M存储区:
                                case MelsecStoreArea.X存储区:
                                case MelsecStoreArea.Y存储区:
                                case MelsecStoreArea.L存储区:
                                case MelsecStoreArea.S存储区:
                                case MelsecStoreArea.B存储区:
                                    //数据读取和解析
                                    res = melsec.melsec.ReadBytes(gp.Start, Convert.ToUInt16(gp.Length));

                                    if (res != null)
                                    {
                                        int gpstart = GetMelsecStart(isFX3U, gp.Start.Substring(1), gp.StoreArea, melsec.IsFX5UMC);

                                        foreach (var var in gp.varList)
                                        {
                                            if (VerifyMelsecAddress(true, isFX3U, gp.StoreArea, var.Start, melsec.IsFX5UMC, out int start, out int offset))
                                            {
                                                switch (var.VarType)
                                                {
                                                    case DataType.Bool:

                                                        var.Value = ByteLib.GetByteFromByteArray(res, start) == 1;
                                                        break;

                                                    default:
                                                        break;
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        melsec.IsConnected = false;
                                    }
                                    break;
                                default:
                                    break;
                            }


                        }
                    }



                    if (!oldindexInitial)
                    {

                        Port1_Loader_Rack_oldIndex = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位1请求搬入载具.Index"]);
                        Port1_Task_Download_oldIndex = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位1请求任务.Index"]);
                        Port1_LoadPCB_oldIndex = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位1请求放板.Index"]);
                        Port1_PanelIDReport_oldIndex = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位1上报PanelID.Index"]);
                        Port1_LotFinishReport_oldIndex = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位1上报完板信息.Index"]);
                        Port1_Unloder_Rack_oldIndex = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位1请求退载具.Index"]);
                        Port1_Allow_Into_oldIndex = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位1AGV请求响应.Index"]);
                        Port2_Loader_Rack_oldIndex = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位2请求搬入载具.Index"]);
                        Port2_Task_Download_oldIndex = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位2请求任务.Index"]);
                        Port2_LoadPCB_oldIndex = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位2请求放板.Index"]);
                        Port2_PanelIDReport_oldIndex = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位2上报PanelID.Index"]);
                        Port2_LotFinishReport_oldIndex = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位2上报完板信息.Index"]);
                        Port2_Unloder_Rack_oldIndex = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位2请求退载具.Index"]);
                        Port3_Loader_Rack_oldIndex = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位3请求搬入载具.Index"]);
                        Port3_Task_Download_oldIndex = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位3请求任务.Index"]);
                        Port3_LoadPCB_oldIndex = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位3请求放板.Index"]);
                        Port3_PanelIDReport_oldIndex = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位3上报PanelID.Index"]);
                        Port3_LotFinishReport_oldIndex = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位3上报完板信息.Index"]);
                        Port3_Unloder_Rack_oldIndex = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位3请求退载具.Index"]);









                        DeviceStatusReport_oldIndex = Convert.ToInt16(CommMethods.CurrentMelsecValue["上报设备状态.Index"]);

                        oldindexInitial = true;
                    }






                }
                else
                {
                    //连接     区分第一次连接和断线重连  

                    if (!melsec.FirstConnect)
                    {
                        Thread.Sleep(melsec.ConnectTimeOut);
                        melsec.melsec.DisConnect();
                    }

                    //涉及到一个枚举类型的转换  NodeSetting  xktComm
                    melsec.melsec = new Melsec(GetMelsecProtocolType(melsec.PlcType), melsec.IsFX5UMC);

                    melsec.melsec.ConnectTimeOut = melsec.ConnectTimeOut;

                    melsec.IsConnected = melsec.melsec.Connect(melsec.IpAddress, melsec.Port);

                    melsec.FirstConnect = false;

                }
            }
        }

        private bool VerifyMelsecAddress(bool isBoolStore, bool isFX3U, MelsecStoreArea store, string address, bool isFX5U, out int start, out int offset)
        {
            if (isBoolStore)
            {
                offset = 0;
                start = 0;
                try
                {
                    start = GetMelsecStart(isFX3U, address, store, isFX5U);
                }
                catch (Exception)
                {

                    return false;
                }
                return true;
            }
            else
            {

                //D10.F     W10.F  D10

                if (address.Contains('.'))
                {
                    string[] result = address.Split('.');

                    offset = 0;
                    start = 0;

                    if (result.Length == 2)
                    {
                        try
                        {
                            start = GetMelsecStart(isFX3U, result[0], store, isFX5U);
                        }
                        catch (Exception)
                        {

                            return false;
                        }

                        try
                        {
                            offset = Convert.ToInt32(result[1], 16);
                        }
                        catch (Exception)
                        {
                            return false;
                        }

                        return true;
                    }
                    else
                    {
                        return false;
                    }

                }
                else
                {
                    offset = 0;
                    start = 0;
                    try
                    {
                        start = GetMelsecStart(isFX3U, address, store, isFX5U);
                    }
                    catch (Exception)
                    {

                        return false;
                    }
                    return true;
                }

            }


        }

        private int GetMelsecStart(bool isFX3U, string start, MelsecStoreArea store, bool isFX5U)
        {

            if (isFX3U)
            {
                switch (store)
                {
                    case MelsecStoreArea.M存储区:
                        return Convert.ToInt32(start, MelsecA1EDataType.M.FromBase);
                    case MelsecStoreArea.X存储区:
                        return Convert.ToInt32(start, MelsecA1EDataType.X.FromBase);
                    case MelsecStoreArea.Y存储区:
                        return Convert.ToInt32(start, MelsecA1EDataType.Y.FromBase);
                    case MelsecStoreArea.D存储区:
                        return Convert.ToInt32(start, MelsecA1EDataType.D.FromBase);
                    case MelsecStoreArea.S存储区:
                        return Convert.ToInt32(start, MelsecA1EDataType.S.FromBase);
                    case MelsecStoreArea.L存储区:
                    case MelsecStoreArea.B存储区:
                    case MelsecStoreArea.W存储区:
                        return 0;
                    default:
                        return 0;
                }


            }


            else
            {
                switch (store)
                {
                    case MelsecStoreArea.M存储区:
                        return Convert.ToInt32(start, MelsecMcDataType.M.FromBase); ;
                    case MelsecStoreArea.X存储区:
                        return isFX5U ? Convert.ToInt32(start, MelsecMcDataType.X5U.FromBase) : Convert.ToInt32(start, MelsecMcDataType.X.FromBase);
                    case MelsecStoreArea.Y存储区:
                        return isFX5U ? Convert.ToInt32(start, MelsecMcDataType.Y5U.FromBase) : Convert.ToInt32(start, MelsecMcDataType.Y.FromBase);
                    case MelsecStoreArea.D存储区:
                        return Convert.ToInt32(start, MelsecMcDataType.D.FromBase);
                    case MelsecStoreArea.L存储区:
                        return Convert.ToInt32(start, MelsecMcDataType.L.FromBase);
                    case MelsecStoreArea.S存储区:
                        return Convert.ToInt32(start, MelsecMcDataType.S.FromBase);
                    case MelsecStoreArea.B存储区:
                        return Convert.ToInt32(start, MelsecMcDataType.B.FromBase);
                    case MelsecStoreArea.W存储区:
                        return Convert.ToInt32(start, MelsecMcDataType.W.FromBase);
                    default:
                        return 0;
                }

            }

        }

        private MelsecProtocolType GetMelsecProtocolType(MelsecProtocol type)
        {

            switch (type)
            {
                case MelsecProtocol.MCBinary:
                    return MelsecProtocolType.MCBinary;
                case MelsecProtocol.MCASCII:
                    return MelsecProtocolType.MCASCII;
                case MelsecProtocol.MCA1E:
                    return MelsecProtocolType.A1EBinary;
                default:
                    return MelsecProtocolType.MCBinary;
            }

        }

        #endregion


        #region 窗体打开和关闭操作
        /// <summary>
        /// 判断MainPanel是否有指定窗体名称的窗体，如果有返回True,否则关闭窗体，返回False
        /// </summary>
        /// <param name="FrmName"></param>
        /// <returns></returns>
        private bool CloseWindow(string FrmName)
        {
            bool Res = false;
            foreach (Control ct in this.MainPanel.Controls)
            {
                if (ct is Form)
                {
                    Form Frm = (Form)ct;
                    if (Frm.Name == FrmName)
                    {
                        Res = true;
                        break;
                    }
                    else
                    {
                        Frm.Close();
                    }

                }
            }
            return Res;
        }

        /// <summary>
        /// 格式化打开窗体
        /// </summary>
        /// <param name="Frm"></param>
        private void OpenWindow(Form Frm)
        {
            Frm.TopLevel = false;
            Frm.FormBorderStyle = FormBorderStyle.None;
            Frm.Dock = DockStyle.Fill;
            Frm.Parent = this.MainPanel;
            Frm.Show();
        }



        //private void Btn_Auto_Click(object sender, EventArgs e)
        //{
        //    if (CloseWindow("Auto_Screen") == false)
        //    {
        //        Auto_Screen objAuto_Screen = new Auto_Screen();

        //        OpenWindow(objAuto_Screen);
        //        BackColorSet("自动画面");

        //        //this.LogTxt.Visible = true;
        //    }
        //}

        //private void Btn_Manual_Click(object sender, EventArgs e)
        //{
        //    if (CloseWindow("Manual_Screen") == false)
        //    {
        //        Manual_Screen objManual_Screen = new Manual_Screen();

        //        OpenWindow(objManual_Screen);
        //        BackColorSet("手动画面");

        //        //this.LogTxt.Visible = true;
        //    }
        //}

        //private void Btn_Alarm_Click(object sender, EventArgs e)
        //{
        //    if (CloseWindow("AlarmReport") == false)
        //    {
        //        AlarmReport objAlarmReport = new AlarmReport();

        //        OpenWindow(objAlarmReport);
        //        BackColorSet("报警履历");

        //        //this.LogTxt.Visible = false;


        //    }
        //}
        //private void Btn_Paraset_Click(object sender, EventArgs e)
        //{
        //    if (CloseWindow("Setting") == false)
        //    {
        //        Setting objSetting = new Setting();

        //        OpenWindow(objSetting);
        //        BackColorSet("参数画面");

        //        //this.LogTxt.Visible = true;

        //    }
        //}

        //private void Btn_IO_Click(object sender, EventArgs e)
        //{
        //    if (CloseWindow("IOView") == false)
        //    {
        //        IOView objIOView = new IOView();

        //        OpenWindow(objIOView);
        //        BackColorSet("设备IO");

        //        //this.LogTxt.Visible = false;


        //    }
        //}


        //private void Btn_Output_Click(object sender, EventArgs e)
        //{
        //    if (CloseWindow("FrmOutputView") == false)
        //    {
        //        FrmOutputView objOutputView = new FrmOutputView();

        //        OpenWindow(objOutputView);
        //        BackColorSet("设备输出");

        //        //this.LogTxt.Visible = false;


        //    }
        //}


        //private void Port_btn_Click(object sender, EventArgs e)
        //{

        //    if (CloseWindow("FrmAGV") == false)
        //    {
        //        FrmAGV objFrmAGV = new FrmAGV();

        //        OpenWindow(objFrmAGV);
        //        BackColorSet("AGV交互");
        //        //this.LogTxt.Visible = false;
        //    }

        //}

        //private void LotMsg_btn_Click(object sender, EventArgs e)
        //{
        //    if (CloseWindow("Frmlot") == false)
        //    {
        //        Frmlot objFrmlot = new Frmlot();

        //        OpenWindow(objFrmlot);
        //        BackColorSet("工单下发");
        //        //this.LogTxt.Visible = false;
        //    }
        //}

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            DialogResult Res = MessageBox.Show("确认注销系统吗？", "退出确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (Res == DialogResult.OK)
            {
                System.Environment.Exit(0);
            }
            else
            {
                e.Cancel = true;
            }
        }

        private void Btn_Exit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        #endregion

        #region 背景颜色改变
        private void BackColorSet(string Item)
        {
            //this.Btn_Auto.BackColor = Color.DodgerBlue;
            //this.Btn_Alarm.BackColor = Color.DodgerBlue;
            //this.Btn_Input.BackColor = Color.DodgerBlue;
            //this.Btn_Manual.BackColor = Color.DodgerBlue;
            //this.Btn_Paraset.BackColor = Color.DodgerBlue;
            //this.Btn_Output.BackColor = Color.DodgerBlue;
            //this.Port_btn.BackColor = Color.DodgerBlue;
            //this.LotMsg_btn.BackColor = Color.DodgerBlue;

            //switch (Item)
            //{
            //    case "自动画面":
            //        this.Btn_Auto.BackColor = Color.Lime;
            //        break;
            //    case "手动画面":
            //        this.Btn_Manual.BackColor = Color.Lime;
            //        break;
            //    case "报警履历":
            //        this.Btn_Alarm.BackColor = Color.Lime;
            //        break;
            //    case "设备IO":
            //        this.Btn_Input.BackColor = Color.Lime;
            //        break;

            //    case "设备输出":
            //        this.Btn_Output.BackColor = Color.Lime;
            //        break;

            //    case "参数画面":
            //        this.Btn_Paraset.BackColor = Color.Lime;
            //        break;
            //    case "AGV交互":
            //        this.Port_btn.BackColor = Color.Lime;
            //        break;

            //    case "工单下发":
            //        this.LotMsg_btn.BackColor = Color.Lime;
            //        break;







            //default:
            //    break;
            //}

        }
        #endregion

        #region 定时器处理
        private void timer1_Tick(object sender, EventArgs e)
        {
            //label33.Text = Port1ReaderBtnTrigger.ToString();
            //       CommMethods.LaserBtnTrigger = true;
            GC.Collect();
            this.lbl_date.Text = DateTime.Now.ToString();

            if (bw.IsBusy == false)
            {
                //       bw.RunWorkerAsync();
            }




            //if (CommMethods.concurrentQueue != null&& CommMethods.concurrentQueue.Count>0)
            //{
            //    //dataGridView1.Columns["job_id"].HeaderText = "批号";
            //    //dataGridView1.Columns["total_panel_count"].HeaderText = "批次数量";
            //    //dataGridView1.Columns["panel_size"].HeaderText = "板子尺寸";

            //    CommMethods.jobDataDownloadList = CommMethods.concurrentQueue.ToList<JobDataDownload>();

            //    CommMethods.jobdataList.Clear();
            //    foreach (var item in CommMethods.jobDataDownloadList)
            //    {
            //        CommMethods.jobdataList.Add(new JobData()
            //        {
            //            job_id = item.job_id,
            //            total_panel_count = item.total_panel_count,
            //            panel_length = item.recipe_parameter_list[0].item_value,
            //            panel_width = item.recipe_parameter_list[1].item_value,
            //            panel_thickness = item.recipe_parameter_list[2].item_value
            //        });
            //    }
            //    this.LotListGridView.DataBindings.Clear();
            //    this.LotListGridView.DataSource = CommMethods.jobdataList; 
            //}




            //       UpdateCommon(this);

            if (CommMethods.MelsecList[0].IsConnected == true)
            {
                this.PLCIsconnected_lamp.LanternBackground = Color.Lime;
            }
            else
            {
                this.PLCIsconnected_lamp.LanternBackground = Color.Red;

                // CommMethods.axActProgType1.Open();
            }

            string StatusValue = CommMethods.CurrentMelsecValue["设备状态"].ToString();
            switch (StatusValue)
            {
                case "0":
                    lbl_Status.Text = "空闲";
                    break;

                case "1":
                    lbl_Status.Text = "忙碌";
                    break;

                case "2":
                    lbl_Status.Text = "故障";
                    break;

                case "3":
                    lbl_Status.Text = "暂停";
                    break;

                case "4":
                    lbl_Status.Text = "保养";
                    break;

                case "5":
                    lbl_Status.Text = "运行";
                    break;

                default:
                    break;
            }


            string strvalue = CommMethods.CurrentMelsecValue["作业模式"].ToString();
            switch (strvalue)
            {
                case "0":
                    control_mode_lbl.Text = "本地模式";
                    break;

                case "1":
                    control_mode_lbl.Text = "远程联机";
                    break;

                default:
                    break;

            }

            strvalue = CommMethods.CurrentMelsecValue["操作模式"].ToString();
            switch (strvalue)
            {
                case "0":
                    operation_mode_lbl.Text = "自动模式";
                    break;

                case "1":
                    operation_mode_lbl.Text = "手动模式";
                    break;

                default:
                    break;
            }

            //strvalue = CommMethods.CurrentMelsecValue["AGV模式"].ToString();
            //switch (strvalue)
            //{
            //    case "0":
            //        work_mode_lbl.Text = "台车模式";
            //        break;

            //    case "1":
            //        work_mode_lbl.Text = "AGV模式";
            //        break;

            //    default:
            //        break;
            //}







            string panel_id_check = CommMethods.CurrentMelsecValue["Panel_ID校验结果"].ToString();

            switch (panel_id_check)
            {
                case "1":
                    check_result_lbl.Text = "NG";
                    break;

                case "2":
                    check_result_lbl.Text = "OK";
                    break;

                default:
                    break;
            }

            string panel_Idvalue = CommMethods.CurrentMelsecValue["PanelID"].ToString();

            if (panel_Idvalue.Contains("#"))
            {
                panel_ID_lbl.Text = panel_Idvalue.Substring(0, panel_Idvalue.IndexOf("#"));
            }
            else
            {
                panel_ID_lbl.Text = "0";
            }

            this.LotID_lbl1.Text = CommMethods.Current_task_info1.lot_num;
            //this.CarrierID_lbl1.Text = CommMethods.Current_task_info1.pallet_num;
            this.LotNumber_lbl1.Text = CommMethods.Current_task_info1.plan_count;
            this.Length_lbl1.Text = CommMethods.Current_task_info1.pallet_length;
            this.width_lbl1.Text = CommMethods.Current_task_info1.pallet_width;
            this.thinkness_lbl1.Text = CommMethods.Current_task_info1.pallet_height;

            this.LotID_lbl2.Text = CommMethods.Current_task_info2.lot_num;
            //this.CarrierID_lbl2.Text = CommMethods.Current_task_info2.pallet_num;
            this.LotNumber_lbl2.Text = CommMethods.Current_task_info2.plan_count;
            this.Length_lbl2.Text = CommMethods.Current_task_info2.pallet_length;
            this.width_lbl2.Text = CommMethods.Current_task_info2.pallet_width;
            this.thinkness_lbl2.Text = CommMethods.Current_task_info2.pallet_height;


            this.LotID_lbl3.Text = CommMethods.Current_task_info3.lot_num;
            //this.CarrierID_lbl3.Text = CommMethods.Current_task_info3.pallet_num;
            this.LotNumber_lbl3.Text = CommMethods.Current_task_info3.plan_count;
            this.Length_lbl3.Text = CommMethods.Current_task_info3.pallet_length;
            this.width_lbl3.Text = CommMethods.Current_task_info3.pallet_width;
            this.thinkness_lbl3.Text = CommMethods.Current_task_info3.pallet_height;







        }





        private void Text_Click(object sender, EventArgs e)
        {
            CommMethods.SetTextValue(sender);
        }

        private void UpdateCommon(Control ctrl)
        {
            foreach (Control item in ctrl.Controls)
            {
                if (item is TextBox Text)
                {
                    if (Text.Tag != null && Text.Tag.ToString().Length > 0)
                    {
                        if (CommMethods.CurrentMelsecValue.ContainsKey(Text.Tag.ToString()))
                        {
                            Text.Text = CommMethods.CurrentMelsecValue[Text.Tag.ToString()].ToString();
                        }
                    }
                }


                else if (item.HasChildren)
                {
                    UpdateCommon(item);
                }

            }

        }


        public void lotDatagridviewUpdate()
        {
            try
            {
                if (CommMethods.concurrentQueue != null && CommMethods.concurrentQueue.Count >= 0)
                {

                    CommMethods.jobDataDownloadList = CommMethods.concurrentQueue.ToList<Task_info>();
                    CommMethods.jobdataList.Clear();
                    foreach (var item in CommMethods.jobDataDownloadList)
                    {

                        CommMethods.jobdataList.Add(new JobData()
                        {
                            job_id = item.lot_num,
                            total_panel_count = item.plan_count,
                            panel_length = item.pallet_length,
                            panel_width = item.pallet_width,
                            panel_thickness = item.pallet_height
                        });
                    }
                }
            }
            catch (Exception ex)
            {

            }

            finally
            {
                //this.LotListGridView.DataSource = null;
                //this.LotListGridView.DataSource = CommMethods.jobdataList;
                if (!this.LotListGridView.InvokeRequired)
                {
                    this.LotListGridView.DataSource = null;
                    if (firstTime == true)
                    {
                        if (CommMethods.jobdataList != null && CommMethods.jobdataList.Count > 0)
                        {
                            this.LotListGridView.DataSource = CommMethods.jobdataList;
                            LotListGridView.Columns["job_id"].HeaderText = "批号";
                            LotListGridView.Columns["total_panel_count"].HeaderText = "批次数量";
                            LotListGridView.Columns["panel_length"].HeaderText = "板子长度";
                            LotListGridView.Columns["panel_width"].HeaderText = "板子宽度";
                            LotListGridView.Columns["panel_thickness"].HeaderText = "板子厚度";

                            LotListGridView.Columns["job_id"].Width = 100;
                            LotListGridView.Columns["total_panel_count"].Width = 100;
                            LotListGridView.Columns["panel_length"].Width = 100;
                            LotListGridView.Columns["panel_width"].Width = 100;
                            LotListGridView.Columns["panel_thickness"].Width = 100;
                            firstTime = false;
                        }
                    }
                    else
                    {
                        this.LotListGridView.DataSource = CommMethods.jobdataList;
                        LotListGridView.Columns["job_id"].HeaderText = "批号";
                        LotListGridView.Columns["total_panel_count"].HeaderText = "批次数量";
                        LotListGridView.Columns["panel_length"].HeaderText = "板子长度";
                        LotListGridView.Columns["panel_width"].HeaderText = "板子宽度";
                        LotListGridView.Columns["panel_thickness"].HeaderText = "板子厚度";

                        LotListGridView.Columns["job_id"].Width = 100;
                        LotListGridView.Columns["total_panel_count"].Width = 100;
                        LotListGridView.Columns["panel_length"].Width = 100;
                        LotListGridView.Columns["panel_width"].Width = 100;
                        LotListGridView.Columns["panel_thickness"].Width = 100;
                    }
                    

                }

                else
                {
                    Invoke(new Action(() =>
                    {
                        this.LotListGridView.DataSource = null;
                        if (firstTime == true)
                        {
                            if (CommMethods.jobdataList != null && CommMethods.jobdataList.Count > 0)
                            {
                                this.LotListGridView.DataSource = CommMethods.jobdataList;
                                LotListGridView.Columns["job_id"].HeaderText = "批号";
                                LotListGridView.Columns["total_panel_count"].HeaderText = "批次数量";
                                LotListGridView.Columns["panel_length"].HeaderText = "板子长度";
                                LotListGridView.Columns["panel_width"].HeaderText = "板子宽度";
                                LotListGridView.Columns["panel_thickness"].HeaderText = "板子厚度";

                                LotListGridView.Columns["job_id"].Width = 100;
                                LotListGridView.Columns["total_panel_count"].Width = 100;
                                LotListGridView.Columns["panel_length"].Width = 100;
                                LotListGridView.Columns["panel_width"].Width = 100;
                                LotListGridView.Columns["panel_thickness"].Width = 100;
                                firstTime = false;
                            }
                        }
                        else
                        {
                            this.LotListGridView.DataSource = CommMethods.jobdataList;
                            LotListGridView.Columns["job_id"].HeaderText = "批号";
                            LotListGridView.Columns["total_panel_count"].HeaderText = "批次数量";
                            LotListGridView.Columns["panel_length"].HeaderText = "板子长度";
                            LotListGridView.Columns["panel_width"].HeaderText = "板子宽度";
                            LotListGridView.Columns["panel_thickness"].HeaderText = "板子厚度";

                            LotListGridView.Columns["job_id"].Width = 100;
                            LotListGridView.Columns["total_panel_count"].Width = 100;
                            LotListGridView.Columns["panel_length"].Width = 100;
                            LotListGridView.Columns["panel_width"].Width = 100;
                            LotListGridView.Columns["panel_thickness"].Width = 100;
                        }

                    }));

                }

            }
        }






        private void timer2_Tick(object sender, EventArgs e)
        {
            if (CommMethods.MelsecList[0].IsConnected)
            {


                CheckAlarm();
                if (AlarmList.Count > 0 && Alarmstrs != null)
                {
                    Alarmstrs = Alarmstrs.Substring(1) + Alarmstrs.Substring(0, 1);
                    lblAlarm_Scrollbar.Text = Alarmstrs;
                }
                else
                {
                    lblAlarm_Scrollbar.Text = "";
                }
            }
            else
            {
                lblAlarm_Scrollbar.Text = "";
            }
        }

        private void timer3_Tick(object sender, EventArgs e)
        {


            //if (SocketIsConnected)
            //  AreyouThereRequest_EQP_Trigger = true;
        }

        #endregion

        #region 初始化报警缓冲集合
        private void InitialAlarm()
        {
            foreach (MelsecVariable item in CommMethods.Alarm_Variable_List)
            {

                LastValue.Add(item.Name, 0);
            }
        }
        #endregion

        #region 报警信息实时解析
        private void CheckAlarm()
        {
            AlarmList.Clear();

            bool flag = false;
            foreach (MelsecVariable item in CommMethods.Alarm_Variable_List)
            {
                string VarName = item.Name;
                int lastValue = LastValue[VarName];
                int currentValue = Convert.ToInt32(CommMethods.CurrentMelsecValue[VarName]);
                if (currentValue == 1) AlarmList.Add(item.Config.DiscreteAlarmNote);
                if (lastValue != currentValue) flag = true;
                if ((currentValue == 1) && (lastValue == 0))
                {
                    string DataTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
                    string TriggerTime = DateTime.Now.ToLongTimeString();
                    string ResTime = "";
                    LogHelper.LogSQLite(item.Name, DataTime, TriggerTime, item.Config.DiscreteAlarmNote, Convert.ToInt16(CommMethods.CurrentMelsecValue[VarName]).ToString(), ResTime);

                }

                if ((currentValue == 0) && (lastValue == 1))
                {
                    string ResTime = DateTime.Now.ToLongTimeString();
                    LogHelper.UpdateTime(VarName, ResTime);
                }
                LastValue[VarName] = Convert.ToInt32(CommMethods.CurrentMelsecValue[VarName]);
            }

            if (flag && (AlarmList.Count > 0))
            {
                Alarmstrs = "";
                foreach (string str in AlarmList)
                {
                    Alarmstrs += str + "         ";
                }
                while (Alarmstrs.Length < 100)
                {
                    Alarmstrs += Alarmstrs;
                }
            }
        }
        #endregion





        #region EAP数据交互流程
        private void EAPprocess()
        {
            while (true)
            {
                if (true)
                {

                    #region 工位1请求搬入载具
                    if ((Port1_Loader_Rack_oldIndex != Convert.ToInt16(CommMethods.CurrentMelsecValue["工位1请求搬入载具.Index"])) || Port1_Loader_Rack_Trigger)
                    {
                        callPalletEvent _callPalletEvent = new callPalletEvent();
                        _callPalletEvent.up_sys_name = up_sys_name;
                        _callPalletEvent.line_code = line_code;
                        _callPalletEvent.station_code = station_code;
                        _callPalletEvent.station_type = station_type;
                        _callPalletEvent.port_code = CommMethods.port1Position;
                        _callPalletEvent.request_uuid = Guid.NewGuid().ToString();
                        _callPalletEvent.request_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        string PostMsg = JsonConvert.SerializeObject(_callPalletEvent);
                        AddLog(1, "工位1请求搬入载具：" + PostMsg);
                        string ResultMsg = client.PostMessage(PostMsg, "callPalletEvent");
                        if (ResultMsg != null)
                        {
                            AddLog(1, "工位1请求搬入载具--->响应：" + ResultMsg);
                            callPalletEventResponse _result = JsonConvert.DeserializeObject<callPalletEventResponse>(ResultMsg);
                            if (_result.success == true)
                            {
                                CommMethods.CommonMelsecWrite(CommMethods.CurrentMelsecVarList["工位1请求搬入载具.Result"], "1");
                            }
                        }
                        Port1_Loader_Rack_oldIndex = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位1请求搬入载具.Index"]);
                        Port1_Loader_Rack_Trigger = false;
                    }
                    #endregion

                    #region 工位2请求搬入载具
                    if ((Port2_Loader_Rack_oldIndex != Convert.ToInt16(CommMethods.CurrentMelsecValue["工位2请求搬入载具.Index"])) || Port2_Loader_Rack_Trigger)
                    {
                        callPalletEvent _callPalletEvent = new callPalletEvent();
                        _callPalletEvent.up_sys_name = up_sys_name;
                        _callPalletEvent.line_code = line_code;
                        _callPalletEvent.station_code = station_code;
                        _callPalletEvent.station_type = station_type;
                        _callPalletEvent.port_code = CommMethods.port2Position;
                        _callPalletEvent.request_uuid = Guid.NewGuid().ToString();
                        _callPalletEvent.request_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        string PostMsg = JsonConvert.SerializeObject(_callPalletEvent);
                        AddLog(1, "工位2请求搬入载具：" + PostMsg);
                        string ResultMsg = client.PostMessage(PostMsg, "callPalletEvent");
                        if (ResultMsg != null)
                        {
                            AddLog(1, "工位2请求搬入载具--->响应：" + ResultMsg);
                            callPalletEventResponse _result = JsonConvert.DeserializeObject<callPalletEventResponse>(ResultMsg);
                            if (_result.success == true)
                            {
                                CommMethods.CommonMelsecWrite(CommMethods.CurrentMelsecVarList["工位2请求搬入载具.Result"], "1");
                            }
                        }
                        Port2_Loader_Rack_oldIndex = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位2请求搬入载具.Index"]);
                        Port2_Loader_Rack_Trigger = false;
                    }
                    #endregion

                    #region 工位3请求搬入载具
                    if ((Port3_Loader_Rack_oldIndex != Convert.ToInt16(CommMethods.CurrentMelsecValue["工位3请求搬入载具.Index"])) || Port3_Loader_Rack_Trigger)
                    {
                        callPalletEvent _callPalletEvent = new callPalletEvent();
                        _callPalletEvent.up_sys_name = up_sys_name;
                        _callPalletEvent.line_code = line_code;
                        _callPalletEvent.station_code = station_code;
                        _callPalletEvent.station_type = station_type;
                        _callPalletEvent.port_code = CommMethods.port3Position;
                        _callPalletEvent.request_uuid = Guid.NewGuid().ToString();
                        _callPalletEvent.request_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        string PostMsg = JsonConvert.SerializeObject(_callPalletEvent);
                        AddLog(1, "工位3请求搬入载具：" + PostMsg);
                        string ResultMsg = client.PostMessage(PostMsg, "callPalletEvent");
                        if (ResultMsg != null)
                        {
                            AddLog(1, "工位3请求搬入载具--->响应：" + ResultMsg);
                            callPalletEventResponse _result = JsonConvert.DeserializeObject<callPalletEventResponse>(ResultMsg);
                            if (_result.success == true)
                            {
                                CommMethods.CommonMelsecWrite(CommMethods.CurrentMelsecVarList["工位3请求搬入载具.Result"], "1");
                            }
                        }
                        Port3_Loader_Rack_oldIndex = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位3请求搬入载具.Index"]);
                        Port3_Loader_Rack_Trigger = false;
                    }
                    #endregion

                    #region 工位1允许进入
                    if (Port1_Allow_Into_Trigger || Port1_Allow_Into_oldIndex != Convert.ToInt16(CommMethods.CurrentMelsecValue["工位1AGV请求响应.Index"]))
                    {
                        ContinueTask _ContinueTaskEvent = new ContinueTask();
                        _ContinueTaskEvent.reqCode=CommMethods.port1ReqCode;
                        _ContinueTaskEvent.taskCode = CommMethods.port1TaskCode;
                        _ContinueTaskEvent.request_uuid = Guid.NewGuid().ToString();
                        _ContinueTaskEvent.request_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        _ContinueTaskEvent.request_attr = "";
                        string PostMsg = JsonConvert.SerializeObject(_ContinueTaskEvent);
                        AddLog(1, "工位1允许进入：" + PostMsg);
                        string ResultMsg = client.PostMessage(PostMsg, "continueTask");
                        if (ResultMsg != null)
                        {
                            AddLog(1, "工位1允许进入--->响应：" + ResultMsg);
                            AgvTaskResponseBase _result = JsonConvert.DeserializeObject<AgvTaskResponseBase>(ResultMsg);
                        }
                        Port1_Allow_Into_oldIndex = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位1AGV请求响应.Index"]);
                        Port1_Allow_Into_Trigger = false;
                    }
                    #endregion

                    #region 工位2允许进入
                    if ( Port2_Allow_Into_oldIndex != Convert.ToInt16(CommMethods.CurrentMelsecValue["工位2AGV请求响应.Index"]))
                    {
                        ContinueTask _ContinueTaskEvent = new ContinueTask();
                        _ContinueTaskEvent.reqCode = CommMethods.port2ReqCode;
                        _ContinueTaskEvent.taskCode = CommMethods.port2TaskCode;
                        _ContinueTaskEvent.request_uuid = Guid.NewGuid().ToString();
                        _ContinueTaskEvent.request_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        _ContinueTaskEvent.request_attr = "";
                        string PostMsg = JsonConvert.SerializeObject(_ContinueTaskEvent);
                        AddLog(1, "工位2允许进入：" + PostMsg);
                        string ResultMsg = client.PostMessage(PostMsg, "continueTask");
                        if (ResultMsg != null)
                        {
                            AddLog(1, "工位2允许进入--->响应：" + ResultMsg);
                            AgvTaskResponseBase _result = JsonConvert.DeserializeObject<AgvTaskResponseBase>(ResultMsg);
                        }
                        Port2_Allow_Into_oldIndex = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位2AGV请求响应.Index"]);
                    }
                    #endregion

                    #region 工位3允许进入
                    if (Port3_Allow_Into_oldIndex != Convert.ToInt16(CommMethods.CurrentMelsecValue["工位3AGV请求响应.Index"]))
                    {
                        ContinueTask _ContinueTaskEvent = new ContinueTask();
                        _ContinueTaskEvent.reqCode = CommMethods.port3ReqCode;
                        _ContinueTaskEvent.taskCode = CommMethods.port3TaskCode;
                        _ContinueTaskEvent.request_uuid = Guid.NewGuid().ToString();
                        _ContinueTaskEvent.request_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        _ContinueTaskEvent.request_attr = "";
                        string PostMsg = JsonConvert.SerializeObject(_ContinueTaskEvent);
                        AddLog(1, "工位3允许进入：" + PostMsg);
                        string ResultMsg = client.PostMessage(PostMsg, "continueTask");
                        if (ResultMsg != null)
                        {
                            AddLog(1, "工位3允许进入--->响应：" + ResultMsg);
                            AgvTaskResponseBase _result = JsonConvert.DeserializeObject<AgvTaskResponseBase>(ResultMsg);
                        }
                        Port3_Allow_Into_oldIndex = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位3AGV请求响应.Index"]);
                    }
                    #endregion



                    #region 工位1请求任务
                    //if ((Port1_Task_Download_oldIndex != Convert.ToInt16(CommMethods.CurrentMelsecValue["工位1请求任务.Index"])) || Port1_Task_Download_Trigger)
                    //{

                    //    askDownTaskEvent _askDownTaskEvent = new askDownTaskEvent();
                    //    _askDownTaskEvent.up_sys_name = up_sys_name;
                    //    _askDownTaskEvent.line_code = line_code;
                    //    _askDownTaskEvent.station_code = station_code;
                    //    _askDownTaskEvent.station_type = station_type;
                    //    _askDownTaskEvent.port_code = "1";
                    //    //_askDownTaskEvent.pallet_num = CommMethods.CurrentMelsecValue["工位1载具ID"].ToString();
                    //    _askDownTaskEvent.request_uuid = Guid.NewGuid().ToString();
                    //    _askDownTaskEvent.request_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    //    string PostMsg = JsonConvert.SerializeObject(_askDownTaskEvent);
                    //    AddLog(1, "工位1主动请求任务：" + PostMsg);
                    //    string ResultMsg = client.PostMessage(PostMsg, "askDownTaskEvent");
                    //    if (ResultMsg != null)
                    //    {
                    //        AddLog(1, "工位1主动请求任务--->响应：" + ResultMsg);
                    //        askDownTaskEventResponse _result = JsonConvert.DeserializeObject<askDownTaskEventResponse>(ResultMsg);
                    //        CommMethods.Current_task_info1 = _result.task_info;

                    //        CommMethods.CommonMelsecWrite(CommMethods.CurrentMelsecVarList["工位1下发.Total_Panel_Count"], CommMethods.Current_task_info1.plan_count);
                    //        CommMethods.CommonMelsecWrite(CommMethods.CurrentMelsecVarList["工位1下发.PCB_Length"], CommMethods.Current_task_info1.pallet_length);
                    //        CommMethods.CommonMelsecWrite(CommMethods.CurrentMelsecVarList["工位1下发.PCB_Width"], CommMethods.Current_task_info1.pallet_width);
                    //        CommMethods.CommonMelsecWrite(CommMethods.CurrentMelsecVarList["工位1下发.PCB_Thinkness"], CommMethods.Current_task_info1.pallet_height);
                    //        short value = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位1下发任务.Index"]);
                    //        value = (short)(value + 1);
                    //        CommMethods.CommonMelsecWrite(CommMethods.CurrentMelsecVarList["工位1下发任务.Index"], value.ToString());
                    //    }
                    //    Port1_Task_Download_oldIndex = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位1请求任务.Index"]);
                    //    Port1_Task_Download_Trigger = false;
                    //}
                    #endregion

                    #region 工位1请求放板
                    //if ((Port1_LoadPCB_oldIndex != Convert.ToInt16(CommMethods.CurrentMelsecValue["工位1请求放板.Index"])) || Port1_LoadPCB_Trigger)
                    //{

                    //    askEapAllowStartEvent _askEapAllowStartEvent = new askEapAllowStartEvent();

                    //    _askEapAllowStartEvent.up_sys_name = up_sys_name;
                    //    _askEapAllowStartEvent.line_code = line_code;
                    //    _askEapAllowStartEvent.station_code = station_code;
                    //    _askEapAllowStartEvent.station_type = station_type;
                    //    _askEapAllowStartEvent.port_code = "A";
                    //    //_askEapAllowStartEvent.pallet_num = CommMethods.CurrentMelsecValue["工位1载具ID"].ToString();
                    //    _askEapAllowStartEvent.lot_num = CommMethods.Current_task_info1.lot_num;
                    //    _askEapAllowStartEvent.request_uuid = Guid.NewGuid().ToString();
                    //    _askEapAllowStartEvent.request_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                    //    string PostMsg = JsonConvert.SerializeObject(_askEapAllowStartEvent);
                    //    AddLog(1, "工位1请求允许放板：" + PostMsg);
                    //    string ResultMsg = client.PostMessage(PostMsg, "askEapAllowStartEvent");
                    //    if (ResultMsg != null)
                    //    {
                    //        AddLog(1, "工位1主动请求任务--->响应：" + ResultMsg);
                    //        askEapAllowStartEventResponse _result = JsonConvert.DeserializeObject<askEapAllowStartEventResponse>(ResultMsg);
                    //    }
                    //    Port1_LoadPCB_oldIndex = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位1请求放板.Index"]);
                    //    Port1_LoadPCB_Trigger = false;
                    //}
                    #endregion

                    #region 工位1上报PanelID
                    if ((Port1_PanelIDReport_oldIndex != Convert.ToInt16(CommMethods.CurrentMelsecValue["工位1上报PanelID.Index"])) || Port1_PanelIDReport_Trigger)
                    {
                        short value;
                        panelResultUpEvent _panelResultUpEvent = new panelResultUpEvent();

                        _panelResultUpEvent.up_sys_name = up_sys_name;
                        _panelResultUpEvent.line_code = line_code;
                        _panelResultUpEvent.station_code = station_code;
                        _panelResultUpEvent.station_type = station_type;
                        _panelResultUpEvent.port_code = CommMethods.port1Position;
                        _panelResultUpEvent.pallet_num = "1";
                        _panelResultUpEvent.lot_num = CommMethods.Current_task_info1.lot_num;
                        _panelResultUpEvent.panel_barcode = SubStringPanelID(CommMethods.CurrentMelsecValue["PanelID"].ToString());

                        if (CommMethods.Current_task_info1.panel_list != null)
                        {
                            if (CommMethods.Current_task_info1.panel_list.Contains(_panelResultUpEvent.panel_barcode))
                            {
                                _panelResultUpEvent.panel_status = "OK";
                                CommMethods.CommonMelsecWrite(CommMethods.CurrentMelsecVarList["Panel_ID校验结果"], "1");
                                _panelResultUpEvent.panel_code = 1;
                                _panelResultUpEvent.panel_msg = "合格";
                            }
                            else
                            {
                                _panelResultUpEvent.panel_status = "NG";
                                CommMethods.CommonMelsecWrite(CommMethods.CurrentMelsecVarList["Panel_ID校验结果"], "2");
                                _panelResultUpEvent.panel_code = 4;
                                _panelResultUpEvent.panel_msg = "不合格";
                            }
                        }
                        else
                        {
                            _panelResultUpEvent.panel_status = "NG";
                            CommMethods.CommonMelsecWrite(CommMethods.CurrentMelsecVarList["Panel_ID校验结果"], "2");
                            _panelResultUpEvent.panel_code = 4;
                            _panelResultUpEvent.panel_msg = "不合格";
                        }
                        value = Convert.ToInt16(CommMethods.CurrentMelsecValue["Panel_ID校验结果.Index"]);
                        value = (short)(value + 1);
                        CommMethods.CommonMelsecWrite(CommMethods.CurrentMelsecVarList["Panel_ID校验结果.Index"], value.ToString());
                        _panelResultUpEvent.panel_index = 1;
                        CommMethods.panelList.Add(new PanelID
                        {
                            panel_barcode = _panelResultUpEvent.panel_barcode,
                            panel_status = _panelResultUpEvent.panel_status,
                            panel_code = _panelResultUpEvent.panel_code,
                            panel_index = _panelResultUpEvent.panel_index,
                            panel_msg = _panelResultUpEvent.panel_msg,
                            panel_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                        });

                        _panelResultUpEvent.request_uuid = Guid.NewGuid().ToString();
                        _panelResultUpEvent.request_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        string PostMsg = JsonConvert.SerializeObject(_panelResultUpEvent);
                        AddLog(1, "工位1上报PanelID：" + PostMsg);
                        string ResultMsg = client.PostMessage(PostMsg, "panelResultUpEvent");
                        if (ResultMsg != null)
                        {
                            AddLog(1, "工位1上报PanelID--->响应：" + ResultMsg);
                            panelResultUpEventResponse _result = JsonConvert.DeserializeObject<panelResultUpEventResponse>(ResultMsg);
                        }
                        Port1_PanelIDReport_oldIndex = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位1上报PanelID.Index"]);
                        Port1_PanelIDReport_Trigger = false;
                    }
                    #endregion

                    #region 工位2上报PanelID
                    if ((Port2_PanelIDReport_oldIndex != Convert.ToInt16(CommMethods.CurrentMelsecValue["工位2上报PanelID.Index"])) || Port2_PanelIDReport_Trigger)
                    {
                        short value;
                        panelResultUpEvent _panelResultUpEvent = new panelResultUpEvent();

                        _panelResultUpEvent.up_sys_name = up_sys_name;
                        _panelResultUpEvent.line_code = line_code;
                        _panelResultUpEvent.station_code = station_code;
                        _panelResultUpEvent.station_type = station_type;
                        _panelResultUpEvent.port_code = CommMethods.port2Position;
                        _panelResultUpEvent.pallet_num = "2";
                        _panelResultUpEvent.lot_num = CommMethods.Current_task_info2.lot_num;
                        _panelResultUpEvent.panel_barcode = SubStringPanelID(CommMethods.CurrentMelsecValue["PanelID"].ToString());

                        if (CommMethods.Current_task_info2.panel_list != null)
                        {
                            if (CommMethods.Current_task_info2.panel_list.Contains(_panelResultUpEvent.panel_barcode))
                            {
                                _panelResultUpEvent.panel_status = "OK";
                                CommMethods.CommonMelsecWrite(CommMethods.CurrentMelsecVarList["Panel_ID校验结果"], "1");
                            }
                            else
                            {
                                _panelResultUpEvent.panel_status = "NG";
                                CommMethods.CommonMelsecWrite(CommMethods.CurrentMelsecVarList["Panel_ID校验结果"], "2");
                            }
                        }
                        else
                        {
                            _panelResultUpEvent.panel_status = "NG";
                            CommMethods.CommonMelsecWrite(CommMethods.CurrentMelsecVarList["Panel_ID校验结果"], "2");
                        }

                        value = Convert.ToInt16(CommMethods.CurrentMelsecValue["Panel_ID校验结果.Index"]);
                        value = (short)(value + 1);
                        CommMethods.CommonMelsecWrite(CommMethods.CurrentMelsecVarList["Panel_ID校验结果.Index"], value.ToString());
                        _panelResultUpEvent.panel_code = 1;
                        _panelResultUpEvent.panel_index = 1;
                        _panelResultUpEvent.panel_msg = "AAA";
                        CommMethods.panelList.Add(new PanelID
                        {
                            panel_barcode = _panelResultUpEvent.panel_barcode,
                            panel_status = _panelResultUpEvent.panel_status,
                            panel_code = _panelResultUpEvent.panel_code,
                            panel_index = _panelResultUpEvent.panel_index,
                            panel_msg = _panelResultUpEvent.panel_msg,
                            panel_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                        });

                        _panelResultUpEvent.request_uuid = Guid.NewGuid().ToString();
                        _panelResultUpEvent.request_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        string PostMsg = JsonConvert.SerializeObject(_panelResultUpEvent);
                        AddLog(1, "工位2上报PanelID：" + PostMsg);
                        string ResultMsg = client.PostMessage(PostMsg, "panelResultUpEvent");
                        if (ResultMsg != null)
                        {
                            AddLog(1, "工位2上报PanelID--->响应：" + ResultMsg);
                            panelResultUpEventResponse _result = JsonConvert.DeserializeObject<panelResultUpEventResponse>(ResultMsg);
                        }
                        Port2_PanelIDReport_oldIndex = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位2上报PanelID.Index"]);
                        Port2_PanelIDReport_Trigger = false;
                    }
                    #endregion

                    #region 工位3上报PanelID
                    if ((Port3_PanelIDReport_oldIndex != Convert.ToInt16(CommMethods.CurrentMelsecValue["工位3上报PanelID.Index"])) || Port3_PanelIDReport_Trigger)
                    {
                        short value;
                        panelResultUpEvent _panelResultUpEvent = new panelResultUpEvent();

                        _panelResultUpEvent.up_sys_name = up_sys_name;
                        _panelResultUpEvent.line_code = line_code;
                        _panelResultUpEvent.station_code = station_code;
                        _panelResultUpEvent.station_type = station_type;
                        _panelResultUpEvent.port_code = CommMethods.port3Position;
                        _panelResultUpEvent.pallet_num = "3";
                        _panelResultUpEvent.lot_num = CommMethods.Current_task_info3.lot_num;
                        _panelResultUpEvent.panel_barcode = SubStringPanelID(CommMethods.CurrentMelsecValue["PanelID"].ToString());

                        if (CommMethods.Current_task_info3.panel_list != null)
                        {
                            if (CommMethods.Current_task_info3.panel_list.Contains(_panelResultUpEvent.panel_barcode))
                            {
                                _panelResultUpEvent.panel_status = "OK";
                                CommMethods.CommonMelsecWrite(CommMethods.CurrentMelsecVarList["Panel_ID校验结果"], "1");
                            }
                            else
                            {
                                _panelResultUpEvent.panel_status = "NG";
                                CommMethods.CommonMelsecWrite(CommMethods.CurrentMelsecVarList["Panel_ID校验结果"], "2");
                            }
                        }
                        else
                        {
                            _panelResultUpEvent.panel_status = "NG";
                            CommMethods.CommonMelsecWrite(CommMethods.CurrentMelsecVarList["Panel_ID校验结果"], "2");
                        }

                        value = Convert.ToInt16(CommMethods.CurrentMelsecValue["Panel_ID校验结果.Index"]);
                        value = (short)(value + 1);
                        CommMethods.CommonMelsecWrite(CommMethods.CurrentMelsecVarList["Panel_ID校验结果.Index"], value.ToString());
                        _panelResultUpEvent.panel_code = 1;
                        _panelResultUpEvent.panel_index = 1;
                        _panelResultUpEvent.panel_msg = "AAA";
                        CommMethods.panelList.Add(new PanelID
                        {
                            panel_barcode = _panelResultUpEvent.panel_barcode,
                            panel_status = _panelResultUpEvent.panel_status,
                            panel_code = _panelResultUpEvent.panel_code,
                            panel_index = _panelResultUpEvent.panel_index,
                            panel_msg = _panelResultUpEvent.panel_msg,
                            panel_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                        });

                        _panelResultUpEvent.request_uuid = Guid.NewGuid().ToString();
                        _panelResultUpEvent.request_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        string PostMsg = JsonConvert.SerializeObject(_panelResultUpEvent);
                        AddLog(1, "工位3上报PanelID：" + PostMsg);
                        string ResultMsg = client.PostMessage(PostMsg, "panelResultUpEvent");
                        if (ResultMsg != null)
                        {
                            AddLog(1, "工位3上报PanelID--->响应：" + ResultMsg);
                            panelResultUpEventResponse _result = JsonConvert.DeserializeObject<panelResultUpEventResponse>(ResultMsg);
                        }
                        Port3_PanelIDReport_oldIndex = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位3上报PanelID.Index"]);
                        Port3_PanelIDReport_Trigger = false;
                    }
                    #endregion

                    #region 工位1上报完板信息
                    if ((Port1_LotFinishReport_oldIndex != Convert.ToInt16(CommMethods.CurrentMelsecValue["工位1上报完板信息.Index"])) || Port1_LotFinishReport_Trigger)
                    {

                        taskTrackFinishEvent _taskTrackFinishEvent = new taskTrackFinishEvent();

                        _taskTrackFinishEvent.up_sys_name = up_sys_name;
                        _taskTrackFinishEvent.line_code = line_code;
                        _taskTrackFinishEvent.station_code = station_code;
                        _taskTrackFinishEvent.station_type = station_type;
                        _taskTrackFinishEvent.port_code = CommMethods.port1Position;
                        //_taskTrackFinishEvent.pallet_num = CommMethods.CurrentMelsecValue["工位1载具ID"].ToString();
                        _taskTrackFinishEvent.lot_num = CommMethods.Current_task_info1.lot_num;
                        _taskTrackFinishEvent.work_order = CommMethods.Current_task_info1.lot_num;
                        _taskTrackFinishEvent.plan_count = Convert.ToInt16(CommMethods.Current_task_info1.plan_count);
                        _taskTrackFinishEvent.finish_count = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位1当前批次数量"]);
                        _taskTrackFinishEvent.finish_ok_count = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位1当前OK数量"]);
                        _taskTrackFinishEvent.finish_ng_count = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位1当前NG数量"]);
                        _taskTrackFinishEvent.panel_list = CommMethods.panelList;
                        _taskTrackFinishEvent.request_uuid = Guid.NewGuid().ToString();
                        _taskTrackFinishEvent.request_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                        string PostMsg = JsonConvert.SerializeObject(_taskTrackFinishEvent);
                        AddLog(1, "工位1上报完板信息：" + PostMsg);
                        string ResultMsg = client.PostMessage(PostMsg, "taskTrackFinishEvent");
                        if (ResultMsg != null)
                        {
                            AddLog(1, "工位1上报完板信息--->响应：" + ResultMsg);

                            taskTrackFinishEventResponse _result = JsonConvert.DeserializeObject<taskTrackFinishEventResponse>(ResultMsg);

                        }
                        CommMethods.panelList.Clear();
                        Save();
                        Port1_LotFinishReport_oldIndex = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位1上报完板信息.Index"]);
                        Port1_LotFinishReport_Trigger = false;
                    }
                    #endregion

                    #region 工位2上报完板信息
                    if ((Port2_LotFinishReport_oldIndex != Convert.ToInt16(CommMethods.CurrentMelsecValue["工位2上报完板信息.Index"])) || Port2_LotFinishReport_Trigger)
                    {

                        taskTrackFinishEvent _taskTrackFinishEvent = new taskTrackFinishEvent();

                        _taskTrackFinishEvent.up_sys_name = up_sys_name;
                        _taskTrackFinishEvent.line_code = line_code;
                        _taskTrackFinishEvent.station_code = station_code;
                        _taskTrackFinishEvent.station_type = station_type;
                        _taskTrackFinishEvent.port_code = CommMethods.port2Position;
                        //_taskTrackFinishEvent.pallet_num = CommMethods.CurrentMelsecValue["工位1载具ID"].ToString();
                        _taskTrackFinishEvent.lot_num = CommMethods.Current_task_info2.lot_num;
                        _taskTrackFinishEvent.work_order = CommMethods.Current_task_info2.lot_num;
                        _taskTrackFinishEvent.plan_count = Convert.ToInt16(CommMethods.Current_task_info2.plan_count);
                        _taskTrackFinishEvent.finish_count = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位2当前批次数量"]);
                        _taskTrackFinishEvent.finish_ok_count = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位2当前OK数量"]);
                        _taskTrackFinishEvent.finish_ng_count = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位2当前NG数量"]);
                        _taskTrackFinishEvent.panel_list = CommMethods.panelList;

                        _taskTrackFinishEvent.request_uuid = Guid.NewGuid().ToString();
                        _taskTrackFinishEvent.request_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                        string PostMsg = JsonConvert.SerializeObject(_taskTrackFinishEvent);
                        AddLog(1, "工位2上报完板信息：" + PostMsg);
                        string ResultMsg = client.PostMessage(PostMsg, "taskTrackFinishEvent");
                        if (ResultMsg != null)
                        {
                            AddLog(1, "工位2上报完板信息--->响应：" + ResultMsg);

                            taskTrackFinishEventResponse _result = JsonConvert.DeserializeObject<taskTrackFinishEventResponse>(ResultMsg);

                        }
                        Port2_LotFinishReport_oldIndex = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位2上报完板信息.Index"]);
                        Port2_LotFinishReport_Trigger = false;
                    }
                    #endregion

                    #region 工位3上报完板信息
                    if ((Port3_LotFinishReport_oldIndex != Convert.ToInt16(CommMethods.CurrentMelsecValue["工位3上报完板信息.Index"])) || Port3_LotFinishReport_Trigger)
                    {

                        taskTrackFinishEvent _taskTrackFinishEvent = new taskTrackFinishEvent();

                        _taskTrackFinishEvent.up_sys_name = up_sys_name;
                        _taskTrackFinishEvent.line_code = line_code;
                        _taskTrackFinishEvent.station_code = station_code;
                        _taskTrackFinishEvent.station_type = station_type;
                        _taskTrackFinishEvent.port_code = CommMethods.port3Position;
                        //_taskTrackFinishEvent.pallet_num = CommMethods.CurrentMelsecValue["工位1载具ID"].ToString();
                        _taskTrackFinishEvent.lot_num = CommMethods.Current_task_info3.lot_num;
                        _taskTrackFinishEvent.work_order = CommMethods.Current_task_info3.lot_num;
                        _taskTrackFinishEvent.plan_count = Convert.ToInt16(CommMethods.Current_task_info3.plan_count);
                        _taskTrackFinishEvent.finish_count = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位3当前批次数量"]);
                        _taskTrackFinishEvent.finish_ok_count = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位3当前OK数量"]);
                        _taskTrackFinishEvent.finish_ng_count = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位3当前NG数量"]);
                        _taskTrackFinishEvent.panel_list = CommMethods.panelList;

                        _taskTrackFinishEvent.request_uuid = Guid.NewGuid().ToString();
                        _taskTrackFinishEvent.request_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                        string PostMsg = JsonConvert.SerializeObject(_taskTrackFinishEvent);
                        AddLog(1, "工位3上报完板信息：" + PostMsg);
                        string ResultMsg = client.PostMessage(PostMsg, "taskTrackFinishEvent");
                        if (ResultMsg != null)
                        {
                            AddLog(1, "工位3上报完板信息--->响应：" + ResultMsg);

                            taskTrackFinishEventResponse _result = JsonConvert.DeserializeObject<taskTrackFinishEventResponse>(ResultMsg);

                        }
                        Port3_LotFinishReport_oldIndex = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位3上报完板信息.Index"]);
                        Port3_LotFinishReport_Trigger = false;
                    }
                    #endregion

                    #region 工位1请求退载具
                    if ((Port1_Unloder_Rack_oldIndex != Convert.ToInt16(CommMethods.CurrentMelsecValue["工位1请求退载具.Index"])) || Port1_Unloder_Rack_Trigger)
                    {

                        askPalletMoveOutEvent _askPalletMoveOutEvent = new askPalletMoveOutEvent();

                        _askPalletMoveOutEvent.up_sys_name = up_sys_name;
                        _askPalletMoveOutEvent.line_code = line_code;
                        _askPalletMoveOutEvent.station_code = station_code;
                        _askPalletMoveOutEvent.station_type = station_type;
                        _askPalletMoveOutEvent.port_code = CommMethods.port1Position;
                        //_askPalletMoveOutEvent.pallet_num = CommMethods.CurrentMelsecValue["工位1载具ID"].ToString();
                        _askPalletMoveOutEvent.lot_num = CommMethods.Current_task_info1.lot_num;
                        _askPalletMoveOutEvent.out_code = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位1请求退载具.Type"]);
                        _askPalletMoveOutEvent.request_uuid = Guid.NewGuid().ToString();
                        _askPalletMoveOutEvent.request_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                        string PostMsg = JsonConvert.SerializeObject(_askPalletMoveOutEvent);
                        AddLog(1, "工位1请求退载具：" + PostMsg);
                        string ResultMsg = client.PostMessage(PostMsg, "askPalletMoveOutEvent");
                        if (ResultMsg != null)
                        {
                            AddLog(1, "工位1请求退载具--->响应：" + ResultMsg);

                            askPalletMoveOutEventResponse _result = JsonConvert.DeserializeObject<askPalletMoveOutEventResponse>(ResultMsg);
                            if (_result.success == true)
                            {
                                CommMethods.CommonMelsecWrite(CommMethods.CurrentMelsecVarList["工位1请求退载具.Result"], "1");
                            }
                        }
                        Port1_Unloder_Rack_oldIndex = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位1请求退载具.Index"]);
                        Port1_Unloder_Rack_Trigger = false;
                    }
                    #endregion

                    #region 工位2请求退载具
                    if ((Port2_Unloder_Rack_oldIndex != Convert.ToInt16(CommMethods.CurrentMelsecValue["工位2请求退载具.Index"])) || Port2_Unloder_Rack_Trigger)
                    {

                        askPalletMoveOutEvent _askPalletMoveOutEvent = new askPalletMoveOutEvent();

                        _askPalletMoveOutEvent.up_sys_name = up_sys_name;
                        _askPalletMoveOutEvent.line_code = line_code;
                        _askPalletMoveOutEvent.station_code = station_code;
                        _askPalletMoveOutEvent.station_type = station_type;
                        _askPalletMoveOutEvent.port_code = CommMethods.port2Position;
                        //_askPalletMoveOutEvent.pallet_num = CommMethods.CurrentMelsecValue["工位1载具ID"].ToString();
                        _askPalletMoveOutEvent.lot_num = CommMethods.Current_task_info2.lot_num;
                        _askPalletMoveOutEvent.out_code = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位2请求退载具.Type"]);
                        _askPalletMoveOutEvent.request_uuid = Guid.NewGuid().ToString();
                        _askPalletMoveOutEvent.request_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                        string PostMsg = JsonConvert.SerializeObject(_askPalletMoveOutEvent);
                        AddLog(1, "工位2请求退载具：" + PostMsg);
                        string ResultMsg = client.PostMessage(PostMsg, "askPalletMoveOutEvent");
                        if (ResultMsg != null)
                        {
                            AddLog(1, "工位2请求退载具--->响应：" + ResultMsg);

                            askPalletMoveOutEventResponse _result = JsonConvert.DeserializeObject<askPalletMoveOutEventResponse>(ResultMsg);
                            if (_result.success == true)
                            {
                                CommMethods.CommonMelsecWrite(CommMethods.CurrentMelsecVarList["工位2请求退载具.Result"], "1");
                            }
                        }
                        Port2_Unloder_Rack_oldIndex = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位2请求退载具.Index"]);
                        Port2_Unloder_Rack_Trigger = false;
                    }
                    #endregion

                    #region 工位3请求退载具
                    if ((Port3_Unloder_Rack_oldIndex != Convert.ToInt16(CommMethods.CurrentMelsecValue["工位3请求退载具.Index"])) || Port3_Unloder_Rack_Trigger)
                    {

                        askPalletMoveOutEvent _askPalletMoveOutEvent = new askPalletMoveOutEvent();

                        _askPalletMoveOutEvent.up_sys_name = up_sys_name;
                        _askPalletMoveOutEvent.line_code = line_code;
                        _askPalletMoveOutEvent.station_code = station_code;
                        _askPalletMoveOutEvent.station_type = station_type;
                        _askPalletMoveOutEvent.port_code = CommMethods.port3Position;
                        //_askPalletMoveOutEvent.pallet_num = CommMethods.CurrentMelsecValue["工位1载具ID"].ToString();
                        _askPalletMoveOutEvent.lot_num = CommMethods.Current_task_info3.lot_num;
                        _askPalletMoveOutEvent.out_code = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位3请求退载具.Type"]);
                        _askPalletMoveOutEvent.request_uuid = Guid.NewGuid().ToString();
                        _askPalletMoveOutEvent.request_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                        string PostMsg = JsonConvert.SerializeObject(_askPalletMoveOutEvent);
                        AddLog(1, "工位3请求退载具：" + PostMsg);
                        string ResultMsg = client.PostMessage(PostMsg, "askPalletMoveOutEvent");
                        if (ResultMsg != null)
                        {
                            AddLog(1, "工位3请求退载具--->响应：" + ResultMsg);

                            askPalletMoveOutEventResponse _result = JsonConvert.DeserializeObject<askPalletMoveOutEventResponse>(ResultMsg);
                            if (_result.success == true)
                            {
                                CommMethods.CommonMelsecWrite(CommMethods.CurrentMelsecVarList["工位3请求退载具.Result"], "1");
                            }
                        }
                        Port3_Unloder_Rack_oldIndex = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位3请求退载具.Index"]);
                        Port3_Unloder_Rack_Trigger = false;
                    }
                    #endregion

                    #region 工位1请求批次下发
                    if ((Port1_Task_Download_oldIndex != Convert.ToInt16(CommMethods.CurrentMelsecValue["工位1请求任务.Index"])) || Port1_Task_Download_Trigger)
                    {
                        if (CommMethods.concurrentQueue != null && CommMethods.concurrentQueue.Count > 0)
                        {
                            var result = CommMethods.concurrentQueue.TryDequeue(out var m);
                            if (result)
                            {

                                CommMethods.Current_task_info1 = m;
                                Save();
                                lotDatagridviewUpdate();
                                AddLog(1, "队列批次信息下发到工位1: " + JsonConvert.SerializeObject(m));
                                //CommMethods.CommonMelsecWrite(CommMethods.CurrentMelsecVarList["工位1下发.Lot_ID"], CommMethods.Current_task_info1.lot_num);
                                CommMethods.CommonMelsecWrite(CommMethods.CurrentMelsecVarList["工位1下发.Total_Panel_Count"], CommMethods.Current_task_info1.plan_count);
                                CommMethods.CommonMelsecWrite(CommMethods.CurrentMelsecVarList["工位1下发.PCB_Length"], CommMethods.Current_task_info1.pallet_length);
                                CommMethods.CommonMelsecWrite(CommMethods.CurrentMelsecVarList["工位1下发.PCB_Width"], CommMethods.Current_task_info1.pallet_width);
                                CommMethods.CommonMelsecWrite(CommMethods.CurrentMelsecVarList["工位1下发.PCB_Thinkness"], CommMethods.Current_task_info1.pallet_height);
                                short value = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位1下发任务.Index"]);
                                value = (short)(value + 1);
                                CommMethods.CommonMelsecWrite(CommMethods.CurrentMelsecVarList["工位1下发任务.Index"], value.ToString());
                            }
                        }
                        Port1_Task_Download_oldIndex = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位1请求任务.Index"]);
                        Port1_Task_Download_Trigger = false;

                    }
                    #endregion

                    #region 工位2请求批次下发
                    if ((Port2_Task_Download_oldIndex != Convert.ToInt16(CommMethods.CurrentMelsecValue["工位2请求任务.Index"])) || Port2_Task_Download_Trigger)
                    {
                        if (CommMethods.concurrentQueue != null && CommMethods.concurrentQueue.Count > 0)
                        {
                            var result = CommMethods.concurrentQueue.TryDequeue(out var m);
                            if (result)
                            {

                                CommMethods.Current_task_info2 = m;
                                Save();
                                lotDatagridviewUpdate();
                                AddLog(1, "队列批次信息下发到工位2: " + JsonConvert.SerializeObject(m));
                                CommMethods.CommonMelsecWrite(CommMethods.CurrentMelsecVarList["工位2下发.Lot_ID"], CommMethods.Current_task_info2.lot_num);
                                CommMethods.CommonMelsecWrite(CommMethods.CurrentMelsecVarList["工位2下发.Total_Panel_Count"], CommMethods.Current_task_info2.plan_count);
                                CommMethods.CommonMelsecWrite(CommMethods.CurrentMelsecVarList["工位2下发.PCB_Length"], CommMethods.Current_task_info2.pallet_length);
                                CommMethods.CommonMelsecWrite(CommMethods.CurrentMelsecVarList["工位2下发.PCB_Width"], CommMethods.Current_task_info2.pallet_width);
                                CommMethods.CommonMelsecWrite(CommMethods.CurrentMelsecVarList["工位2下发.PCB_Thinkness"], CommMethods.Current_task_info2.pallet_height);
                                short value = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位2下发任务.Index"]);
                                value = (short)(value + 1);
                                CommMethods.CommonMelsecWrite(CommMethods.CurrentMelsecVarList["工位2下发任务.Index"], value.ToString());
                            }
                        }
                        Port2_Task_Download_oldIndex = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位2请求任务.Index"]);
                        Port2_Task_Download_Trigger = false;

                    }

                    #endregion

                    #region 工位3请求批次下发
                    if ((Port3_Task_Download_oldIndex != Convert.ToInt16(CommMethods.CurrentMelsecValue["工位3请求任务.Index"])) || Port3_Task_Download_Trigger)
                    {
                        if (CommMethods.concurrentQueue != null && CommMethods.concurrentQueue.Count > 0)
                        {
                            var result = CommMethods.concurrentQueue.TryDequeue(out var m);
                            if (result)
                            {

                                CommMethods.Current_task_info3 = m;
                                Save();
                                lotDatagridviewUpdate();
                                AddLog(1, "队列批次信息下发到工位3: " + JsonConvert.SerializeObject(m));
                                CommMethods.CommonMelsecWrite(CommMethods.CurrentMelsecVarList["工位3下发.Lot_ID"], CommMethods.Current_task_info3.lot_num);
                                CommMethods.CommonMelsecWrite(CommMethods.CurrentMelsecVarList["工位3下发.Total_Panel_Count"], CommMethods.Current_task_info3.plan_count);
                                CommMethods.CommonMelsecWrite(CommMethods.CurrentMelsecVarList["工位3下发.PCB_Length"], CommMethods.Current_task_info3.pallet_length);
                                CommMethods.CommonMelsecWrite(CommMethods.CurrentMelsecVarList["工位3下发.PCB_Width"], CommMethods.Current_task_info3.pallet_width);
                                CommMethods.CommonMelsecWrite(CommMethods.CurrentMelsecVarList["工位3下发.PCB_Thinkness"], CommMethods.Current_task_info3.pallet_height);
                                short value = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位3下发任务.Index"]);
                                value = (short)(value + 1);
                                CommMethods.CommonMelsecWrite(CommMethods.CurrentMelsecVarList["工位3下发任务.Index"], value.ToString());
                            }
                        }
                        Port3_Task_Download_oldIndex = Convert.ToInt16(CommMethods.CurrentMelsecValue["工位3请求任务.Index"]);
                        Port3_Task_Download_Trigger = false;

                    }

                    #endregion

                    #region 上报设备状态
                    if ((DeviceStatusReport_oldIndex != Convert.ToInt16(CommMethods.CurrentMelsecValue["上报设备状态.Index"])) || DeviceStatusReport_Trigger)
                    {

                        upDeviceStatusEvent _upDeviceStatusEvent = new upDeviceStatusEvent();
                        _upDeviceStatusEvent.up_sys_name = up_sys_name;
                        _upDeviceStatusEvent.line_code = line_code;
                        _upDeviceStatusEvent.station_code = station_code;
                        _upDeviceStatusEvent.station_type = station_type;

                        switch (Convert.ToInt16(CommMethods.CurrentMelsecValue["设备状态"]))
                        {
                            case 0:
                                _upDeviceStatusEvent.device_status = "IDLE";
                                break;

                            case 1:
                                _upDeviceStatusEvent.device_status = "BUSY";
                                break;

                            case 2:
                                _upDeviceStatusEvent.device_status = "ALARM";
                                break;

                            case 3:
                                _upDeviceStatusEvent.device_status = "STOP";
                                break;

                            case 4:
                                _upDeviceStatusEvent.device_status = "KEEP";
                                break;

                            case 5:
                                _upDeviceStatusEvent.device_status = "RUN";
                                break;

                            default:
                                break;
                        }

                        _upDeviceStatusEvent.control_model = Convert.ToInt16(CommMethods.CurrentMelsecValue["操作模式"]) == 0 ? "ON" : "OFF";

                        _upDeviceStatusEvent.task_model = Convert.ToInt16(CommMethods.CurrentMelsecValue["作业模式"]) == 0 ? "LOCAL" : "REMOTE";

                        _upDeviceStatusEvent.request_uuid = Guid.NewGuid().ToString();
                        _upDeviceStatusEvent.request_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                        string PostMsg = JsonConvert.SerializeObject(_upDeviceStatusEvent);
                        AddLog(1, "上报设备状态：" + PostMsg);
                        string ResultMsg = client.PostMessage(PostMsg, "upDeviceStatusEvent");
                        if (ResultMsg != null)
                        {
                            AddLog(1, "上报设备状态--->响应：" + ResultMsg);

                            upDeviceStatusEventResponse _result = JsonConvert.DeserializeObject<upDeviceStatusEventResponse>(ResultMsg);

                        }
                        DeviceStatusReport_oldIndex = Convert.ToInt16(CommMethods.CurrentMelsecValue["上报设备状态.Index"]);
                        DeviceStatusReport_Trigger = false;
                    }
                    #endregion

                    #region 上报设备报警信息
                    if ((EquipmentAlarm1_old != Convert.ToInt32(CommMethods.CurrentMelsecValue["设备严重报警"])) || (EquipmentAlarm2_old != Convert.ToInt32(CommMethods.CurrentMelsecValue["设备一般报警"])))
                    {

                        bool[] equipmentalarm1 = new bool[32];
                        bool[] equipmentalarmold1 = new bool[32];
                        bool[] equipmentalarm2 = new bool[32];
                        bool[] equipmentalarmold2 = new bool[32];


                        equipmentalarm1 = CommMethods.GetbitfromInt(Convert.ToInt32(CommMethods.CurrentMelsecValue["设备严重报警"]));
                        equipmentalarmold1 = CommMethods.GetbitfromInt(EquipmentAlarm1_old);

                        equipmentalarm2 = CommMethods.GetbitfromInt(Convert.ToInt32(CommMethods.CurrentMelsecValue["设备一般报警"]));
                        equipmentalarmold2 = CommMethods.GetbitfromInt(EquipmentAlarm2_old);


                        upDeviceAlarmEvent _upDeviceAlarmEvent = new upDeviceAlarmEvent();

                        _upDeviceAlarmEvent.up_sys_name = up_sys_name;
                        _upDeviceAlarmEvent.line_code = line_code;
                        _upDeviceAlarmEvent.station_code = station_code;
                        _upDeviceAlarmEvent.station_type = station_type;
                        _upDeviceAlarmEvent.alarm_list = new List<Alarm>();


                        for (int i = 0; i < 31; i++)
                        {
                            if (equipmentalarm1[i] == true && equipmentalarmold1[i] == false)
                            {
                                _upDeviceAlarmEvent.alarm_list.Add(new Alarm
                                {
                                    alarm_code = "A" + (i + 1).ToString(),
                                    alarm_msg = typeof(FrmMain).GetField("HAlarm_Msg" + i.ToString()).GetValue(this).ToString(),
                                    alarm_level = 1,
                                    alarm_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                                    alarm_value = 1,
                                });

                            }

                            if (equipmentalarm1[i] == false && equipmentalarmold1[i] == true)
                            {
                                _upDeviceAlarmEvent.alarm_list.Add(new Alarm
                                {
                                    alarm_code = "A" + (i + 1).ToString(),
                                    alarm_msg = typeof(FrmMain).GetField("HAlarm_Msg" + i.ToString()).GetValue(this).ToString(),
                                    alarm_level = 1,
                                    alarm_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                                    alarm_value = 0,
                                });


                            }

                        }

                        for (int i = 0; i < 31; i++)
                        {
                            if (equipmentalarm2[i] == true && equipmentalarmold2[i] == false)
                            {
                                _upDeviceAlarmEvent.alarm_list.Add(new Alarm
                                {
                                    alarm_code = "A" + (i + 33).ToString(),
                                    alarm_msg = typeof(FrmMain).GetField("LAlarm_Msg" + i.ToString()).GetValue(this).ToString(),
                                    alarm_level = 1,
                                    alarm_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                                    alarm_value = 1,
                                });

                            }

                            if (equipmentalarm2[i] == false && equipmentalarmold2[i] == true)
                            {
                                _upDeviceAlarmEvent.alarm_list.Add(new Alarm
                                {
                                    alarm_code = "A" + (i + 33).ToString(),
                                    alarm_msg = typeof(FrmMain).GetField("LAlarm_Msg" + i.ToString()).GetValue(this).ToString(),
                                    alarm_level = 1,
                                    alarm_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                                    alarm_value = 1,
                                });

                            }

                        }


                        _upDeviceAlarmEvent.request_uuid = Guid.NewGuid().ToString();
                        _upDeviceAlarmEvent.request_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                        string PostMsg = JsonConvert.SerializeObject(_upDeviceAlarmEvent);
                        AddLog(1, "上报设备报警信息：" + PostMsg);
                        string ResultMsg = client.PostMessage(PostMsg, "upDeviceAlarmEvent");
                        if (ResultMsg != null)
                        {
                            AddLog(1, "上报设备报警信息--->响应：" + ResultMsg);
                            upDeviceAlarmEventResponse _result = JsonConvert.DeserializeObject<upDeviceAlarmEventResponse>(ResultMsg);
                        }
                            EquipmentAlarm1_old = Convert.ToInt32(CommMethods.CurrentMelsecValue["设备严重报警"]);
                            EquipmentAlarm2_old = Convert.ToInt32(CommMethods.CurrentMelsecValue["设备一般报警"]);                  
                    }
                    #endregion


                }
            }
        }
        #endregion


        #region RESFUL服务打开
        private void Restfful() 
        {
            MesRestService demoService = new MesRestService(this);

            demoService.LogEvent += AddLog;

            Uri baseAddress = new Uri(ServerURL);
            WebServiceHost _serviceHost = new WebServiceHost(demoService, baseAddress);
            //如果不设置MaxBufferSize,当传输的数据特别大的时候，很容易出现“提示:413 Request Entity Too Large”错误信息,最大设置为20M
            WebHttpBinding binding = new WebHttpBinding
            {
                TransferMode = TransferMode.Buffered,
                MaxBufferSize = 2147483647,
                MaxReceivedMessageSize = 2147483647,
                MaxBufferPoolSize = 2147483647,
                ReaderQuotas = System.Xml.XmlDictionaryReaderQuotas.Max,
                Security = { Mode = WebHttpSecurityMode.None }
            };
            _serviceHost.AddServiceEndpoint(typeof(IMesRestService), binding, baseAddress);
            _serviceHost.Open();
        }

        #endregion



        
        private string SubStringPanelID(string str)
        {
            if (str.Contains("#"))
            {
                return str.Substring(0, str.IndexOf("#"));
            }
            else
            {
                return "";
            }
        }




        private string CurrentTime
        {
            //get { return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); }

            get { return DateTime.Now.ToString("yyyyMMddHHmmssffff"); }


        }
        private string CurrentTime1
        {
            get { return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); }




        }
        private bool IsHourInteger()
        {
            if ((DateTime.Now.Minute == 0) && (DateTime.Now.Second == 0))

                return true;

            else
                return false;
        }

        private string HexGetString(byte[] buffer, int start, int length)
        {
            string Result = string.Empty;

            if (buffer != null && buffer.Length >= start + length)
            {
                //截取字节数组

                byte[] res = new byte[length];

                Array.Copy(buffer, start, res, 0, length);

                string Hex = Encoding.Default.GetString(res, 0, res.Length);

                // 01   03 0 40 0A
                if (Hex.Contains(" "))
                {
                    string[] str = Regex.Split(Hex, "\\s+", RegexOptions.IgnoreCase);

                    foreach (var item in str)
                    {
                        Result += "0x" + item + " ";
                    }
                }
                else
                {
                    Result += "0x" + Hex;
                }

            }
            else
            {
                Result = "Error";
            }
            return Result;
        }

        private void AddLog(int index, string info)
        {
            //if (!this.lst_Rcv.InvokeRequired)
            //{
            //    ListViewItem lst = new ListViewItem("   " + CurrentTime1, index);

            //    lst.SubItems.Add(info);

            //    lst_Rcv.Items.Insert(lst_Rcv.Items.Count, lst);

            //}
            //else
            //{
            //    Invoke(new Action(() =>
            //    {
            //        ListViewItem lst = new ListViewItem("   " + CurrentTime1, index);

            //        lst.SubItems.Add(info);

            //        lst_Rcv.Items.Insert(lst_Rcv.Items.Count, lst);
            //    }));

            if (!this.lst_Rcv.InvokeRequired)
            {
                ListViewItem lst = new ListViewItem(DateTime.Now.ToString());
                lst.SubItems.Add(info);
                this.lst_Rcv.Items.Add(lst);
                this.lst_Rcv.Items[this.lst_Rcv.Items.Count - 1].EnsureVisible();
            }
            else
            {
                Invoke(new Action(() =>
                {
                    ListViewItem lst = new ListViewItem(DateTime.Now.ToString());
                    lst.SubItems.Add(info);
                    this.lst_Rcv.Items.Add(lst);
                    this.lst_Rcv.Items[this.lst_Rcv.Items.Count - 1].EnsureVisible();
                }));
                //this.lst_Rcv.Invoke(new Action<int, string>(AddLog), index, info);
            }

            WriteEAPlog(info);
        }

        public void WriteEAPlog(string msg)
        {
            string logPath = Application.StartupPath + "/EAPlog.txt";
            StreamWriter sw = File.AppendText(logPath);
            sw.WriteLine(DateTime.Now.ToString() + msg);
            sw.Close();
            sw.Dispose();
        }

        public void Writelog(string msg)
        {
            string logPath = Application.StartupPath + "/log.txt";
            StreamWriter sw = File.AppendText(logPath);
            sw.WriteLine(DateTime.Now.ToString() + msg);
            sw.Close();
            sw.Dispose();
        }

        //工位1上报PanelID
        private void button2_Click(object sender, EventArgs e)
        {

            Port1_PanelIDReport_Trigger = true;

        }



        //控制模式上报
        private void button4_Click(object sender, EventArgs e)
        {

            CommMethods.CurrentMelsecValue["设备状态"] = "1";
            DeviceStatusReport_Trigger = true;
        }


        //报警信息上报
        private void button5_Click(object sender, EventArgs e)
        {
            CommMethods.CurrentMelsecValue["设备严重报警"] = AlarmCode_txt.Text.Trim();


        }


        //工位1请求退载具
        private void button8_Click(object sender, EventArgs e)
        {

            Port1_Unloder_Rack_Trigger = true;
        }

        //工位1请求任务
        private void button9_Click(object sender, EventArgs e)
        {

            Port1_Task_Download_Trigger = true;
        }







        //队列信息保存到文件
        public void Save()
        {

            if (CommMethods.concurrentQueue != null)
            {
                var str = JsonConvert.SerializeObject(CommMethods.concurrentQueue);
                var str1 = JsonConvert.SerializeObject(CommMethods.Current_task_info1);



                File.WriteAllText("concurrentQueue.json", JsonConvert.SerializeObject(CommMethods.concurrentQueue));
                File.WriteAllText("CurrentJobData1.json", JsonConvert.SerializeObject(CommMethods.Current_task_info1));
                File.WriteAllText("CurrentJobData2.json", JsonConvert.SerializeObject(CommMethods.Current_task_info2));
                File.WriteAllText("CurrentJobData3.json", JsonConvert.SerializeObject(CommMethods.Current_task_info3));
                File.WriteAllText("panelList.json", JsonConvert.SerializeObject(CommMethods.panelList));
                //         CommMethods.CommonMelsecWrite(CommMethods.CurrentMelsecVarList["队列数量"], (CommMethods.concurrentQueue.Count).ToString());
            }
            


        }



        // 清除全部队列对象
        private void button10_Click(object sender, EventArgs e)
        {
            bool result = true;
            while (CommMethods.concurrentQueue.Count > 0)
            {
                result = CommMethods.concurrentQueue.TryDequeue(out var m);
            }

            Save();

            lotDatagridviewUpdate();
        }










        //工位1上报完板信息
        private void button11_Click(object sender, EventArgs e)
        {

            Port1_LotFinishReport_Trigger = true;
        }


        private void Btn_MouseDown(object sender, MouseEventArgs e)
        {
            CommMethods.SetBtnValue(sender, "1");
        }

        private void Btn_MouseUp(object sender, MouseEventArgs e)
        {
            CommMethods.SetBtnValue(sender, "0");
        }





        //工位1请求载具
        private void button14_Click_1(object sender, EventArgs e)
        {
            Port1_Loader_Rack_Trigger = true;
        }

        //工位1请求放板
        private void button17_Click(object sender, EventArgs e)
        {
            Port1_LoadPCB_Trigger = true;
        }











        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            new DataGridViewStyle().DgvRowPostPaint(this.LotListGridView, e);
        }

        private void lbl_date_Click(object sender, EventArgs e)
        {

        }

        private void hslButton1_Click(object sender, EventArgs e)
        {
            Save();
            Application.Exit();
        }


        //单批清除
        private void button20_Click(object sender, EventArgs e)
        {
            bool result = CommMethods.concurrentQueue.TryDequeue(out var m);

            if (result)
            {
                Save();

                lotDatagridviewUpdate();
            }
        }

        private void lst_Rcv_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
        {
            StringFormat format = new StringFormat();
            format.Alignment = StringAlignment.Near;
            e.DrawBackground();
            e.Graphics.FillRectangle(Brushes.Blue, e.Bounds);   //设置背景颜色
            Font font = new Font("微软雅黑", 15, FontStyle.Regular);      //设置字体大小
            e.Graphics.DrawString(e.Header.Text, font, Brushes.White, e.Bounds, format); //设置字体颜色

        }

        private void lst_Rcv_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
        {
            e.DrawBackground();
            e.DrawText();
        }

        private void Oprate_Mode_lbl_Click(object sender, EventArgs e)
        {

        }

        private void lst_Rcv_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void lst_Rcv_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            ListViewItem selectedrow = lst_Rcv.SelectedItems[0];

            string a = selectedrow.SubItems[1].Text;
            DetailMessageFrm objdetailMessageFrm = new DetailMessageFrm(a);

            objdetailMessageFrm.Show();
        }

        private void button15_Click(object sender, EventArgs e)
        {
            //      bool Result = CommMethods.MelsecList[0].melsec.Write("D4031", "1234AB");

            byte[] a = ByteArrayLib.GetByteArrayFromString("12345", Encoding.ASCII);

            bool Result1 = CommMethods.MelsecList[0].melsec.Write("D4031", ByteArrayLib.GetByteArrayFromString("12345", Encoding.ASCII));


        }

        private void button13_Click(object sender, EventArgs e)
        {
            Port2_Loader_Rack_Trigger = true;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Port2_PanelIDReport_Trigger = true;
        }

        private void button6_Click(object sender, EventArgs e)
        {
            Port2_Task_Download_Trigger = true;
        }

        private void button7_Click(object sender, EventArgs e)
        {
            Port2_LotFinishReport_Trigger = true;
        }

        private void button12_Click(object sender, EventArgs e)
        {
            Port2_LoadPCB_Trigger = true;
        }

        private void button3_Click_1(object sender, EventArgs e)
        {
            Port2_Unloder_Rack_Trigger = true; 
        }

        private void button15_Click_1(object sender, EventArgs e)
        {
            Port3_Loader_Rack_Trigger = true;
        }

        private void button16_Click(object sender, EventArgs e)
        {
            Port3_PanelIDReport_Trigger = true;
        }

        private void button9_Click_1(object sender, EventArgs e)
        {
            Port3_LotFinishReport_Trigger = true;
        }

        private void button6_Click_1(object sender, EventArgs e)
        {
            Port3_Unloder_Rack_Trigger = true;
        }

        private void button12_Click_1(object sender, EventArgs e)
        {
            Port1_Allow_Into_Trigger = true;
        }
    }
}
